How to Enable CORS from Nodejs server

柔情痞子 提交于 2019-12-02 02:33:24

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

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

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