node.js express 跨域访问

最近在做一个简单的游戏排行服务时,采用node.js + express框架,POST请求时发现存在跨域问题,method总是变成OPTIONS,查找了多个网站才得到解决。以下是解决办法:

//设置跨域访问
app.use(function (req, res, next) {
  if (req.method === "OPTIONS") {
    let headers = {};
    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 {
    res.setHeader("Access-Control-Allow-Origin", "*");
    next();
  }
});

 

posted @ 2018-12-10 18:19  随风的博客  阅读(855)  评论(0编辑  收藏  举报