为啥 NodeJS 服务器发送被 CORS 策略阻止:当很多人使用 API 时没有“访问控制允许来源”

Posted

技术标签:

【中文标题】为啥 NodeJS 服务器发送被 CORS 策略阻止:当很多人使用 API 时没有“访问控制允许来源”【英文标题】:Why NodeJS server sends blocked by CORS policy: No 'Access-Control-Allow-Origin when many people use API为什么 NodeJS 服务器发送被 CORS 策略阻止:当很多人使用 API 时没有“访问控制允许来源” 【发布时间】:2022-01-04 07:09:16 【问题描述】:

我对 NodeJS 中的 CORS 有疑问。这是我在子域 api.mydomainname.com.pl 上工作的 API 代码,它与我在 Angular 中在域 mydomainname.com.pl 上创建的 Web 应用程序进行通信。

import express from 'express';
import bodyParser from 'body-parser';
import * as dotenv from 'dotenv';
import morgan from 'morgan';
import swaggerUI from 'swagger-ui-express';
import * as swaggerDoc from './swagger.json';
import * as http from 'http';
import cors from 'cors';

dotenv.config();

import publicRoutes from './routes/public';
import siteRoutes from './utils/site';
import userRoutes from './routes/user';
import refereeRoutes from './routes/referee';
import adminRoutes from './routes/admin';
import emptyRoutes from './routes/empty';
import deviceRoutes from './routes/device';
import  apiRatelimit  from './utils/ddos_protection';
import * as socketIO from './utils/socket';
import * as JWT from './utils/jwt';
import * as auth from './utils/auth';
import * as Nodemailer from './utils/nodemailer'

const hostName = '127.0.0.1';
const app = express();
const httpServer = http.createServer(app);
const corsOptions = 
    origin: ['https://test.robomotion.com.pl', 'https://robomotion.com.pl', 'http://localhost:4200'],
    optionsSuccessStatus: 200,
    methods: ['GET', 'POST', 'DELETE', 'UPDATE', 'PUT'],
    allowedHeaders: ['Content-Type', 'x-requested-with', 'Authorization', 'Accept', 'token'],
    maxAge: 86400
;

const io = socketIO.default.init(httpServer,  cors: corsOptions );
const nodemailer = Nodemailer.default.init();

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

const port = Number(process.env.SERVER_PORT) || 8080;

app.use("/api-docs", swaggerUI.serve, swaggerUI.setup(swaggerDoc));

app.use(apiRatelimit); //DDOS prtection

app.use(bodyParser.json( limit: '50mb' ));
app.use(express.urlencoded( extended: true ))

app.use(morgan('short'));

app.use(cors(corsOptions));

app.use('/site', siteRoutes);
app.use('/public', publicRoutes);
app.use('/user', JWT.default.verify, auth.default.authorize(0), userRoutes);
app.use('/referee', JWT.default.verify, auth.default.authorize(1), refereeRoutes);
app.use('/admin', JWT.default.verify, auth.default.authorize(2), adminRoutes);
app.use('/device', auth.default.authorize(3), deviceRoutes);

app.use(emptyRoutes); //When can't resolve the path

const server = httpServer.listen(port, hostName, () => 
    console.log(`Server running at http://$hostName:$port`);
);

此配置在大多数客户端上运行良好,但有一小部分用户收到此错误:从源“https://api.mydomainname.com”访问“https://mydomainname.com.pl”处的 XMLHttpRequest .pl' 已被 CORS 策略阻止:没有'Access-Control-Allow-Origin'(Screenshot)。此外,如果很少有用户(大约 10 个)同时使用我的应用程序,this error occurs。 你知道为什么会出现这个问题吗?你认为这是客户端(Angular)还是服务器端(NodeJS)的问题? 提前感谢您的帮助。

【问题讨论】:

这能回答你的问题吗? How to enable cors nodejs with express? 【参考方案1】:

问题是https://api.mydomainname.com.pl 不在您的允许来源列表中。

如果您还想为此源启用 CORS,则需要编辑配置。

const corsOptions = 
    origin: ['https://test.robomotion.com.pl', 'https://robomotion.com.pl', 'http://localhost:4200', 'https://api.mydomainname.com.pl'],
    optionsSuccessStatus: 200,
    methods: ['GET', 'POST', 'DELETE', 'UPDATE', 'PUT'],
    allowedHeaders: ['Content-Type', 'x-requested-with', 'Authorization', 'Accept', 'token'],
    maxAge: 86400
;

【讨论】:

以上是关于为啥 NodeJS 服务器发送被 CORS 策略阻止:当很多人使用 API 时没有“访问控制允许来源”的主要内容,如果未能解决你的问题,请参考以下文章

使用 axios cors 策略错误配置 nodejs rest api 服务器和 vue 项目

服务器端http请求是否具有相同的跨域策略?

为啥只有 Angular 才会出现 CORS 错误? [复制]

在 ajax 发布请求中,我的应用被 CORS 策略错误阻止

如何修复 XMLHttpRequest 已被 CORS 策略阻止

CORS:为啥我的浏览器不发送 OPTIONS 预检请求?