小编典典

如何从Node.js服务器启用CORS

reactjs

我正在使用react将数据发送到我的API。我发出的每个POST请求都会给我一个OPTIONS请求,我需要解决这个问题。我认为我可能需要做一些预检结构,但是在阅读了有关该文件的信息后,我仍然不知道如何实现它。

目前,我正以这种方式连接到我的API …

fetch('http://localhost:8080/login', {
        method: 'POST',
        mode:'cors',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: this.state.username,
            password: this.state.password
        })
    });

这称为onSubmit。我正在向POST请求发送一些数据,所以我假设我需要这些标头。

现在在我的节点js服务器API中,我有以下处理程序…

var responseHeaders = {  
    "access-control-allow-origin": "*",
    "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
    "access-control-allow-headers": "content-type, accept",
    "access-control-max-age": 10,
    "Content-Type": "application/json"
};

app.post('/login', function(req, res, next) {
    if (req.method == "OPTIONS") {
        res.writeHead(statusCode, responseHeaders);
        res.end();
    }
    console.log("hello");
   ...

但是,这不起作用,当我发出请求时,我得到…

OPTIONS /login 200 8.570 ms - 4

如果我删除标题,则POST可以工作,但不会传递数据(用户名,密码)。

如何绕过这个OPTIONS问题?


阅读 294

收藏
2020-07-22

共1个答案

小编典典

app.post顾名思义,用于POST请求。OPTIONS请求不会路由到该方法。

您需要编写特定于此类选项的处理程序,

app.options("*",function(req,res,next){
  res.header("Access-Control-Allow-Origin", req.get("Origin")||"*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   //other headers here
    res.status(200).end();
});
2020-07-22