Javascript 无法使用fetch api从Express server获取JSON

Javascript 无法使用fetch api从Express server获取JSON,javascript,express,cors,es6-promise,fetch-api,Javascript,Express,Cors,Es6 Promise,Fetch Api,在运行于8080端口的Express服务器中,我有 app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "http://localhost:8081"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); 来自端口8081

在运行于8080端口的Express服务器中,我有

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:8081");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
来自端口8081的请求

fetch('http://localhost:8080/...')
      .then((response) => response.json())
      .then((json) => {
        let jsonStr = JSON.stringify(json);
        console.log(jsonStr)
      })
      .catch((error) => console.log(error))
我得到的错误是:

Access to fetch at 'http://localhost:8080/...' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
如果我只是在浏览器上手动输入expressurl,我就会看到我试图获取的JSON

我已经阅读了多篇文章来解决这个问题,但我似乎仍然无法解决它


如何提取以避免此错误

您正在从另一个端口(8081)获取数据,这就是为什么会收到CORS错误消息。按如下方式更改访问控制策略:

  res.header("Access-Control-Allow-Origin", "http://localhost:*");

这可以派上用场。

您可以使用
cors
来摆脱这一问题

const express = require('express')
const cors = require('cors')
const app = express()

app.use(cors())

@如果我尝试过安装和使用cors,但没有成功,我怀疑您可能在API路由之后初始化了cors。请检查。@Vid,是的,在初始化cors之前不再出现同样的错误,但是我没有定义JSON