nodejs 解决跨域

Posted 童彪

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nodejs 解决跨域相关的知识,希望对你有一定的参考价值。

app.all(‘*‘, function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ‘ 3.2.1‘);
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

  

if (req.method === ‘OPTIONS‘) {
      console.log(‘!OPTIONS‘);
      var headers = {};
      // IE8 does not allow domains to be specified, just the *
      // headers["Access-Control-Allow-Origin"] = req.headers.origin;
      headers["Access-Control-Allow-Origin"] = "*";
      headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
      headers["Access-Control-Allow-Credentials"] = false;
      headers["Access-Control-Max-Age"] = ‘86400‘; // 24 hours
      headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
      res.writeHead(200, headers);
      res.end();
} else {
//...other requests
}

  

“简单请求”
 请求方法是以下三种方法之一:
HEAD
GET
POST

“非简单请求”
HTTP的头信息不超出以下几种字段:
Accept
Accept-Language
Content-Language
Last-Event-ID
Content-Type:
application/x-www-form-urlencoded、 multipart/form-data、text/plain
不满足这些特征的请求称为“非简单请求”,例如:content-type=applicaiton/json , method = PUT/DELETE...













以上是关于nodejs 解决跨域的主要内容,如果未能解决你的问题,请参考以下文章

nodejs作为前后端分离中间件的跨域解决方案

Nodejs代理解决开发环境下跨域问题

解决vue nodejs中cros跨域cookie和session失效的问题

nodejs做http请求转发,解决js跨域问题(二)

Nodejs解决所有跨域请求

nodejs 跨域解决问题