提问者:小点点

设置express+react,CORS


嘿,我正试着把工作变成我的快车和react Local在一起。 我开始在localhost:3000上进行react操作,并在4040上进行express操作,但不知何故,我的cors不能工作。 我在server.js中允许所有cors资料:

var allowedOrigins = ['http://localhost:3000',
    'http://127.0.0.1:3000', '*'];
app.use(cors({
    origin: function(origin, callback){
        // allow requests with no origin
        // (like mobile apps or curl requests)
        if(!origin) return callback(null, true);
        if(allowedOrigins.indexOf(origin) === -1){
            var msg = 'The CORS policy for this site does not ' +
                'allow access from the specified Origin.';
            return callback(new Error(msg), false);
        }
        return callback(null, true);
    }
}));


app.options('/attendant', function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader('Access-Control-Allow-Methods', '*');
    res.setHeader("Access-Control-Allow-Headers", "*");
    res.end();
}); 

但在尝试从express中获取数据之后,在我的react中,我仍然得到:

CORS策略阻止了在“http://localhost/4040/attendant”处从源“http://localhost:3000”提取数据的访问:请求的资源上不存在“Access-Control-Allow-Origin”标头。 如果不透明响应满足您的需要,请将请求的模式设置为“no-cors”,以便在禁用CORS的情况下获取资源。

我错过了什么?


共2个答案

匿名用户

在事务中应用路由和中间件的顺序。

您需要在需要它的路由之前分配cors中间件,否则它将不会被运行。

由于access-control-allow-origin标头报告为丢失,因此您必须以其他顺序分配它们。

更改顺序:

app.use(cors()); // No need to use any options. "Everything" is the default, and you included everything in your list.
app.get('/attendant', (req, res) => res.send('Hello World!'))

匿名用户

我可能偶然发现了一个错误:您的路由'/attendant'必须响应GET请求。 试试这个,告诉我它是否有效!

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

const cors = require('cors')

app.use(cors())

app.get('/attendant', function (req, res) {
  res.json({msg: 'It works'})
})

app.listen(4040, function () {
  console.log('Server running on port 4040')
})

如果要设置话务路由的选项,可能应该使用app.all()

app.all('/attendant', function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', '*');
  res.setHeader("Access-Control-Allow-Headers", "*");
  next(); // pass control to the next handler
});

有关更多信息,请参阅以下文档:https://expressjs.com/fr/guide/routing.html和https://expressjs.com/en/resources/middleware/cors.html