我的Express.js服务器在端口3001上运行,我的React前端在端口3000上运行。我已经使用npm install cors --save
设置了cors npm包,并将其配置为:
var express = require('express');
var cors = require('cors');
var app = express();
var router = express.Router();
app.use(cors());
服务器正在运行并响应Postman上的请求。但是,在尝试GET
我的数据时,客户端会出现此错误:
XMLHttpRequest cannot load localhost:3001/api/comments.
Cross origin requests are only supported for protocol schemes:
http, data, chrome, chrome-extension, https, chrome-extension-resource.
__________________________
(anonymous) @ VM455:1
dispatchXhrRequest @ xhr.js:175
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
createError.js:15 Uncaught (in promise) Error: Network Error
etc.
我设置了cors包只有在我的server.js文件中手动设置我的标题后出现此问题:
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
next();
});
我找不到任何有关正确设置CORS中间件但仍有错误的人的信息。我尝试了各种不同的配置(包括主机名和cors包的其他选项,例如在this answer等),但没有成功。我不确定我可以采取哪些措施来进一步解决这个问题。
编辑:检查我的邮递员响应显示正确返回CORS标头:
Access-Control-Allow-Credentials →true
Access-Control-Allow-Headers →Access-Control-Allow-Headers, Origin, Accept, X- Requested-With, Content-Type, Access-Control-Request-Method, Access-Control- Request-Headers
Access-Control-Allow-Methods →GET, HEAD, OPTIONS, POST, PUT, DELETE
Access-Control-Allow-Origin →*