简体   繁体   English

如何正确设置ExpressJs API CORS

[英]How to get ExpressJs API CORS set up properly

I have a Single Page Application(SPA) using axios that tries to get information from a ExpressJS Api running on the same server. 我有一个使用axios的单页应用程序(SPA),它试图从在同一服务器上运行的ExpressJS Api获取信息。

In the SPA axios settings I have the following: 在SPA axios设置中,我具有以下内容:

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

and in the API i am using the npm package cors like this: 在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

This works fine when running locally, but when putting the api on a server (using a node application) I get CORS errors: 在本地运行时,此方法工作正常,但是将api放置在服务器上(使用节点应用程序)时,出现CORS错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at mysite.com. 跨域请求被阻止:“相同来源策略”不允许在mysite.com上读取远程资源。 (Reason: CORS request did not succeed). (原因:CORS请求未成功)。

I can access the api directly from browser and get a response without problems (since it isn't using cross reference) but at least I know the API is running. 我可以直接从浏览器访问api并获得响应,而不会出现问题(因为它没有使用交叉引用),但是至少我知道该API正在运行。

I have tried creating the following (before I define my routes) instead without success: 我尝试创建以下内容(在定义路线之前),但未成功:

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

What am I doing wrong? 我究竟做错了什么?

It's really strange, to allow anything you have to just write app.use(cors()) and it should work probably now it dont work because after app.use(cors()) you write: 真的很奇怪,允许任何事情app.use(cors())需要编写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();
});

then you should try with just cors() middleware. 那么您应该尝试使用cors()中间件。 In order to set cors properly check cors`s documentation. 为了正确设置cors,请检查cors的文档。 Documentation 文献资料

The reason why this did not work was because the web hotel where I hosted my ExpressJS api had not set up their nginx web server proxy so that it could accept the OPTIONS request properly and return with Access-Control-Allow-Origin: api.site.com 之所以不起作用,是因为我托管ExpressJS api的网络酒店未设置其nginx Web服务器代理,因此它可以正确接受OPTIONS请求并返回带有Access-Control-Allow-Origin: api.site.com

If you need more information regarding the setup of cors have a look at these links 如果您需要有关cors设置的更多信息,请查看以下链接

CORS express not working predictably CORS表示无法正常工作

How do I host a web application and an API from the same server while keeping them in separate? 如何在同一服务器上托管Web应用程序和API,同时将它们分开放置?

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API? 为什么不将CORS标头添加到OPTIONS路由允许浏览器访问我的API?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM