nestjs cors 跨域设置

main.ts添加  
app.enableCors(corsOptionsDelegate);
 
 
 
 
import { Request } from 'express';
//设置允许访问的域名
const allowlist = ['http://localhost:8080'];
const corsOptionsDelegate = (req: Request, callback) => {
    let corsOptions;
    console.log("req.header('Origin')",req.header('Origin'))
    if (allowlist.indexOf(req.header('Origin')) !== -1) {
        console.log("req.header('Origin')",req.header('Origin'))
  //如果你不需要 Cookie 可以设置为 *
  // credentials 与前端的axios 的withCredentials(XMLHttpRequest.withCredentials)
   // 同时 origin必须设置为访问域 才能正常访问,主要是为了 凭证是 Cookie ,授权标头或 TLS 客户端证书
        corsOptions = { origin: req.header('Origin'),credentials : true }; 
    } else {
        corsOptions = { origin: false }; // disable CORS for this request
    }
    callback(null, corsOptions); // callback expects two parameters: error and options
}

export default corsOptionsDelegate
posted @   羽鱼  阅读(1040)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
历史上的今天:
2019-05-10 keep-alive vue组件缓存避免多次加载相应的组件
点击右上角即可分享
微信分享提示