【问题标题】:Enabling CORS on Node/Express Not Working在 Node/Express 上启用 CORS 不起作用
【发布时间】:2017-04-19 10:49:49
【问题描述】:

我花了几个小时试图弄清楚这一点......

app.use(function(req, res, next) { 
  res.header('Access-Control-Allow-Origin', "*"); 
  res.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE'); 
  res.header('Access-Control-Allow-Headers', 'Content-Type'); 
  next();
});

app.all('*', function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "X-Requested-With");
   next();
});

对我没用...我的服务器 app.js 中有这个,就在顶部的要求之后。

还尝试了 npm install cors 和 app.use(cors())。也没用。

为什么我会遇到这个问题?我正在使用 express-generator (npm install express-generator)

【问题讨论】:

  • 似乎您在您的应用程序前面使用了一些网络服务器(apache,nginx),有些东西正在剥离该标头。我正在使用cors,效果很好。请记住在路由处理程序之前添加自定义标头,因为快速路由是一组中间件,它们的顺序可能是您问题的根源。
  • 试着把:app.use(cors())放在app = express()之后

标签: node.js express cors


【解决方案1】:
req.open("GET", "localhost:3001/quote");

应该是……

req.open("GET", "http://localhost:3001/quote");

标题不是问题。

【讨论】:

    猜你喜欢
    • 2017-08-15
    • 1970-01-01
    • 2018-10-30
    • 2018-03-05
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多