Fetch:我在 DevTools 中看到了响应,但 Fetch 仍然给我一个 GET 的 "Access-Control-Allow-Origin" 问题

Fetch: I see the response in the DevTools but Fetch still gives me an "Access-Control-Allow-Origin" issue for GET

所以我有一个关于 fetchAccess-Control-Allow-Origin 的问题。

我试着像这样获取一些网站:

fetch('https://localhost/.../api/json')
    .then(blob => blob.json())
    .then(data => console.log("data:", data))
    .catch(err => console.log("err: ", err));

所以在 Chrome 网络选项卡中,我看到显然没有问题。 但是,在 JavaScript 代码中,我遇到了 CORS 个问题。这怎么可能呢?参见:

我试过添加 mode: 'cors' 但没有用。我尝试添加 mode: 'no-cors' 是的,它通过了,但在这种情况下我无法阅读答案,我得到 Unexpected end of input 并且 'blob' 变量无论如何都是空的。

如果我不使用任何选项或 headers 使用 PostmanCurl 执行相同的 GET 请求,它就像一个魅力,我得到了我的回应。

你有什么想法吗? 提前致谢

编辑:因为它在 PostmannCurl 上工作并且因为我可以在 Chrome 调试器中看到响应,所以我不认为它是另一个问题是,请求显然转到了不允许从其他地方访问的外部 URL。对吗?

Edit2:是否可能必须这样做地址:https://localhost 是 self-signed,因此没有有效证书?在 curl 中,我必须添加 --insecure 标志。

正如 T.J 指出的那样。 Crowder,这在浏览器中是不可能做到的。查看相关资源:

但是,不要绝望!有一个解决方法:

cURL 服务器解决方法:

我们将使用调用cURL的节点服务器来绕过限制:

你需要 nodejs 和 npm。

  • npm initnpm i -S express
  • 添加一个 api.js 文件。使用以下代码:
    const https = require("https");
    const express = require('express');

    const app = express();

    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
    });

    app.get('/', function (req, res) {
        const exec = require('child_process').exec;

        exec('curl ' + req.query.url + ' --insecure', function (error, stdout, stderr) {
          console.log('stdout: ' + stdout);
          console.log('stderr: ' + stderr);

          res.json(stdout);

          if (error !== null) {
            console.log('exec error: ' + error);
          }
        });
    });

    app.listen(3000, function () { console.log('listening on port 3000!'); });
  • 运行 服务器通过 node api.js
  • 现在,在您的代码中,您可以向 localhost:3000 发出请求,并在查询参数中添加要发出 get 请求的 url。示例:
    fetch('http://localhost:3000/?url=https://HOST/.../api/json')
      .then(blob => blob.json())
      .then(data => console.log("data:", data))
      .catch(err => console.log("err: ", err));
  • 请求现在按预期工作。享受。