How to Enable CORS from Nodejs server

柔情痞子 提交于 2019-12-20 03:05:50

问题


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.

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

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

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

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

How can I bypass this OPTIONS problem?


回答1:


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



回答2:


The browser sends a preflight Options requests to the server to check if CORS is enabled on the server. To enable cors on the server side add this to your server code

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



回答3:


If you are using Express.js just install cors:

npm install cors

Then you add it like this:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())


来源:https://stackoverflow.com/questions/39990550/how-to-enable-cors-from-nodejs-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!