使用http和https以及CORS问题进行Express服务器设置

时间:2015-02-11 10:50:18

标签: express cors

我在express server.js中有这样的配置:

  app.use(function (request, response, next) {
   response.header('Access-Control-Allow-Origin', '*');
   response.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
   response.header(
    'Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, X-Api-Key'
  );

  next();
})

app.options('*', function (request, response) {
  response.send(200);
});

app.listen(httpPort, function () {
  console.log('Listening on port: ' + httpPort);
});

httpsServer = https.createServer(credentials, app);
httpsServer.listen(httpsPort, function () {
  console.log('Listening on port: ' + httpsPort);
});

我还要指出: https://local:8000http://local:8001

我正试图从http://local:8001拨打电话https://local:8001/api,但收到CORS问题:

阻止跨源请求:同源策略禁止在https://local:8000/api/读取远程资源。这可以通过将资源移动到同一域或启用CORS来解决。

在Chrome上我得到了:

XMLHttpRequest无法加载https://local:8000/。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“http://local:8001”访问。

如何在快速服务器上对CORS的问题进行排序

1 个答案:

答案 0 :(得分:0)

这解决了我的问题:

app.use(function(req, res, next) {  
  res.header('Access-Control-Allow-Origin', 'http://local:8001');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header(
    'Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, X-Api-Key'
  );
  res.header('Access-Control-Allow-Credentials', 'true');
  if ('OPTIONS' === req.method) {
    res.sendStatus(200);
  }
  else {
    next();
  }
});