一点介绍:
跨域资源共享aka CORS 是一种使用附加 HTTP 标头 告诉浏览器让在一个来源(例如http://localhost:3000)运行的Web 应用程序访问来自不同来源(例如http://localhost:8080)的选定资源。换句话说,当 Web 应用程序请求的资源与其自己的来源(域、协议或端口)不同时,它会执行跨域 HTTP 请求。出于安全原因,浏览器会限制从脚本发起的跨域 HTTP 请求。
Access-Control-Allow-Origin 标头确定允许哪些来源通过 CORS 访问服务器资源。
如何解决 CORS 问题?
您可以通过创建Express 中间件自己完成。这是相应的代码sn-p:
// Enable CORS for specific origins:
app.use((req, res, next) => {
// Allow multiple predefined origins
const allowedOrigins = ["https://deployed-app.com", "http://localhost:3000"];
const origin = req.headers.origin; // extract the origin from the header
if (allowedOrigins.indexOf(origin) > -1) { // if the origin is present in our array
res.setHeader("Access-Control-Allow-Origin", origin); // set the CORS header on the response
}
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next(); // move on to the next middleware
});
或者,您可以接受所有请求,
但此选项仅适用于您正在开发或您的 API 是公开的 :)
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
next();
});
此外,还有一个Express CORS 中间件,您可以这样使用它:
npm install cors --save
启用所有 CORS 请求:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`CORS-enabled server is up on ${port}`);
});
为单个路由启用 CORS
const express = require('express');
const cors = require('cors');
const app = express();
app.get('/products/:id', cors(), (req, res, next) => {
res.json({msg: 'This is CORS-enabled for a Single Route'})
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`CORS-enabled server is up on ${port}`);
});
重要提示: 说到 Express 中间件,顺序非常重要。因此,请确保在可能依赖它的任何其他控制器/路由/中间件之前启用 CORS。