我有一个关于NodeJS中CORS的问题。这是我在子域API.mydomainname.com.pl上工作的API代码,它与我在域mydomainname.com.pl.上的Angular中创建的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}`);
});
此配置在大多数客户端上运行良好,但也有一小部分用户会收到此错误:访问位于"的XMLHttpRequesthttps://mydomainname.com.pl'来自原点'https://api.mydomainname.com.pl'已被CORS策略阻止:No'Access Control Allow Origin'(屏幕截图(。此外,如果很少有用户(大约10个(同时使用我的应用程序,就会出现此错误。你知道为什么会出现这个问题吗?你认为这是客户端(在Angular中(还是服务器端(在NodeJS中(的问题?提前感谢您的帮助。
问题在于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
};