解决Node.js跨域请求问题

在使用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');
});

  • 11
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值