Node.js express 跨域问题
发布于 11 年前 作者 ldjking 90175 次浏览 最后一次编辑是 8 年前 来自 问答

跨域问题主要在header上下功夫 首先提供一个w3c的header定义 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html 再提供一个网友提供的header详解 http://kb.cnblogs.com/page/92320/ 这两个有助于帮助大家理解header的类型和作用, 但是遗憾的是跨域相关的两个header属性我都没有找到相关的定义, 下面直接告诉大家 1是Access-Control-Allow-Origin 允许的域 2是Access-Control-Allow-Headers 允许的header类型

第一项可以直接设为* 表示任意 但是第二项不能这样写,在chrome中测试跨域发现报错, 最终的代码看起来是这个样子:

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    if(req.method=="OPTIONS") res.send(200);/*让options请求快速返回*/
    else  next();
});
12 回复

根据上边的代码的完善

//allow custom header and CORS
app.all('*',function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

  if (req.method == 'OPTIONS') {
    res.send(200); /让options请求快速返回/
  }
  else {
    next();
  }
});

原文在这里 解决NodeJS+Express模块的跨域访问控制问题:Access-Control-Allow-Origin - 推酷

@ImCaos 有cors模块的

我只加了 res.header('Access-Control-Allow-Origin', '*'); 也没啥问题。

@i5ting 多谢推荐,今天也研究了一下,发现很不错。 链接expressjs/cors

@hezedu 如果要自己定义请求头部的话,还需要加上 res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'); 这句

@hezedu 客户端定义自己的请求头部 [yourHeaderFeild] 可以是任意一个头部属性,该属性是客户端和服务端约定的头部属性。

@ldjking 我这样解决后发现每次访问后台都会给前台分配一个新的session,请问这个怎么解决呀

回到顶部