【问题标题】:How to Enable CORS from Nodejs server如何从 Nodejs 服务器启用 CORS
【发布时间】:2017-02-20 18:43:33
【问题描述】:

我正在使用 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 问题?

【问题讨论】:

标签: node.js reactjs preflight


【解决方案1】:

浏览器向服务器发送预检选项请求以检查服务器上是否启用了 CORS。要在服务器端启用 cors,请将其添加到您的服务器代码中

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();
    });

【讨论】:

    【解决方案2】:

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

    您需要像这样为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();
    });
    

    【讨论】:

    • 好的,这捕获了选项请求,但是 POST 请求仍然没有被读取,我有点需要它来传递数据。
    • 没有错误,上面的选项请求似乎有效。但是后来我的 POST 处理程序在 OPTIONS 处理程序之后不起作用
    猜你喜欢
    • 2019-08-14
    • 2018-01-30
    • 1970-01-01
    • 2019-01-28
    • 2015-09-01
    • 2019-12-24
    • 1970-01-01
    • 2020-12-28
    • 2018-01-03
    相关资源
    最近更新 更多