【问题标题】:How to get ExpressJs API CORS set up properly如何正确设置 ExpressJs API CORS
【发布时间】:2020-01-07 14:42:12
【问题描述】:

我有一个使用 axios 的单页应用程序 (SPA),它试图从同一服务器上运行的 ExpressJS Api 获取信息。

在 SPA axios 设置中,我有以下内容:

headers: {
 'Access-Control-Allow-Origin': '*',
 'Authorization': store.getters.token,
 'user': store.getters.user
},

在 API 中,我使用的是这样的 npm 包 cors:

const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors');

const app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());

const indexRouter = require('./routes/index');
const adminRouter = require('./routes/adminRoute');
// More routes

app.use('/api', indexRouter);
app.use('/api/admin', adminRouter);
app.use('/api/user', userRouter);
// using more routes

这在本地运行时工作正常,但是将 api 放在服务器上时(使用节点应用程序)我得到 CORS 错误:

跨域请求被阻止:同源策略不允许读取 mysite.com 上的远程资源。 (原因:CORS 请求未成功)。

我可以直接从浏览器访问 api 并获得没有问题的响应(因为它没有使用交叉引用),但至少我知道 API 正在运行。

我尝试创建以下内容(在我定义我的路线之前)但没有成功:

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

我做错了什么?

【问题讨论】:

    标签: node.js express cors


    【解决方案1】:

    这不起作用的原因是因为我托管我的 ExpressJS api 的网络酒店没有设置他们的 nginx 网络服务器代理,以便它可以正确接受 OPTIONS 请求并返回Access-Control-Allow-Origin: api.site.com

    如果您需要有关 cors 设置的更多信息,请查看这些链接

    CORS express not working predictably

    How do I host a web application and an API from the same server while keeping them in separate?

    Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

    https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests

    【讨论】:

      【解决方案2】:

      真的很奇怪,允许任何你必须写的东西 app.use(cors()) 并且它应该工作现在它可能不工作因为在 app.use(cors()) 之后你写:

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

      那么你应该尝试只使用 cors() 中间件。为了正确设置 cors,请检查 cors 的文档。 Documentation

      【讨论】:

      • 您好,是的,当然我分别尝试了这些 :) 啊,现在我看到我发布了一个包含两者的集体代码。对不起
      猜你喜欢
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 2021-10-31
      • 2022-10-15
      • 2014-11-09
      • 2022-06-30
      相关资源
      最近更新 更多