在使用node.js过程中当我们遇到跨域请求的问题时
只需要添加这一段代码到index.js文件中去就可以
app.all('*', function (req, res, next) {
// 允许来自任何源的跨域请求
res.header("Access-Control-Allow-Origin", '*');
// 允许使用的HTTP方法
res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
// 允许的HTTP头列表,这里被注释掉了,可以根据需要取消注释并配置
// res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,token,unitId,unitid,userId,userid' + (Config.AccessControlAllow.Headers ? ',' + Config.AccessControlAllow.Headers : ''));
// 继续其他路由处理
next();
});
如果你想更完整一点
// 引入Express
const express = require('express');
const app = express();
// CORS中间件配置
app.use((req, res, next) => {
// 根据环境设置允许的来源,这里假设生产环境只允许一个指定的域名
const allowedOrigins = ['http://example.com', 'https://example.com'];
const origin = req.headers.origin;
if (process.env.NODE_ENV === 'development' || allowedOrigins.includes(origin)) {
res.header("Access-Control-Allow-Origin", origin);
}
// 设置允许的HTTP方法
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
// 设置允许的HTTP头部,包括一些常用的头部
res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization, Content-Length, X-Custom-Header');
// 处理预检请求
if (req.method === 'OPTIONS') {
// 预检请求无需继续传递到其他中间件
res.status(200).end();
} else {
// 对于其他类型的请求,继续执行后续的中间件
next();
}
});
// 其他的路由和中间件
app.get('/', (req, res) => {
res.send('Hello World!');
});
// 监听端口
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});