如何从Node.js服务器启用CORS [英] How to Enable CORS from Nodejs server

查看:465
本文介绍了如何从Node.js服务器启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using react to send data to my API. Every POST request I make gives me an OPTIONS request, and I need to fix this. I think I might need to do some preflight structure but after reading about it I still do not know how to implement it.

此刻,我正以这种方式连接到我的API ...

At the moment I am connecting to my API as so...

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请求发送一些数据,所以我假设我需要这些标头.

This is called onSubmit. I am sending some data to my POST request so I am assuming I need those headers.

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

Now in my node js server API I have the following handler...

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");
   ...

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

This does not work however, when I make a request I get...

OPTIONS /login 200 8.570 ms - 4

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

If I remove the headers the POST works but the data (username, password) is not passed through.

如何绕过此OPTIONS问题?

How can I bypass this OPTIONS problem?

推荐答案

app.post对于POST请求. OPTIONS请求不会路由到该方法.

app.post is as the name implies, for POST requests. OPTIONS request won't get routed to that method.

您需要像这样编写选项专用的处理程序,

You need to write a handler specific for options like so,

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

这篇关于如何从Node.js服务器启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆