【问题标题】:Express server setup with http and https and CORS issue带有 http 和 https 以及 CORS 问题的快速服务器设置
【发布时间】:2015-04-11 17:02:55
【问题描述】:

我在 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”标头。因此,不允许访问 Origin 'http://local:8001'。

如何在 express 服务器上使用 CORS 对问题进行排序

【问题讨论】:

    标签: express cors


    【解决方案1】:

    这解决了我的问题:

    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();
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多