nodejs各种框架跨域设置

2,590 阅读2分钟

在每次遇到跨域问题,再设置后端跨域配置的时候都会重新在笔记中查找,所以没在这里总结一下各种框架的跨域配置。

nodejs

设置配置。

  • 这里需要注意的是Access-Control-Allow-Origin不能是*号。 这样浏览器就不会拦截服务器设置的cookie了。
  • 因为设置允许携带cookie之后那么请求头Access-Control-Allow-Origin的值就不能设置为*,所以要另外指向一个。
// 设置允许跨域的源
 res.setHeader("Access-Control-Allow-Origin",req.headers.origin);  
 // 设置cookie允许跨域
 res.setHeader("Access-Control-Allow-Credentials"true);  
 // 设置可以跨域的请求方法
 res.setHeader("Access-Control-Request-Method""PUT,POST,GET,DELETE,OPTIONS");

前端需要设置cookie跨域设置。请求头中设置withCredentials: true。这里默认情况下在跨域请求,浏览器是不带 cookie 的。但是我们可以通过设置 withCredentials 来进行传递 cookie。

egg.js

启用插件

    // plugin.js
    exports.cors = {
        enable: true,
        package: 'egg-cors'
    }

设置配置

  // config.default.js

  config.security = {
    csrf: {
      enable: false
    },
    // 设置跨域白名单
    domainWhiteList: [
      'http://localhost:8080',
      'http://127.0.0.1:8080',
    ],
  };

  config.cors = {
    credentials: true,   // 开启认证//允许Cook可以跨域credentials
    allowMethods: "GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS"
  };

可以自己手动设置请求origin通过

    // config/config.default.js
    exports.cors = {
      origin: function ({ req }) {
        const { origin } = req.headers;
        // 配置允许访问白名单
        const whiteList = [
          'http://localhost:7001',
          'http://127.0.0.1:7001',
        ];
        if (whiteList.includes(origin)) {
          return origin;
        }
      },
      credentials: true,   // 开启认证//允许Cook可以跨域credentials
      allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
    };

express

通过插件完成

    // 引入跨域插件
    const cors = require('cors'); 
    // 解决跨域
    app.use(cors());
    
    // 手动覆盖cors跨域默认设置
    const whitelist = ['http://127.0.0.1:8080', 'http://localhost:8080']
    const corsOptions = {
      origin: function (origin, callback) {
        if (whitelist.indexOf(origin) !== -1) {
          callback(null, true)
        } else {
          callback(new Error('Not allowed by CORS'))
        }
      },
      credentials: true
    }
    app.use(cors(corsOptions));

通过手动配置中间件

app.all("*", (req, res, next) => {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header("Access-Control-Allow-Credentials", true); // ++ 新增
  // 设置可以跨域的请求方法
  res.header("Access-Control-Request-Method""PUT,POST,GET,DELETE,OPTIONS");
  next();
});

koa

通过插件

    const cors = require('koa2-cors'); 
    const app = new Koa(); 
    app.use(cors());
    // 或者自己配置各个头的值。
    app.use(cors({
      originfunction(ctx) {
        if (ctx.url === '/test') {
          return "*";
        }
        return ctx.headers.origin;
      },
      credentialstrue,
      allowMethods: ['GET''POST''DELETE']
    }));

通过手动配置中间件

   app.use(async (ctx, next)=> {
      ctx.set('Access-Control-Allow-Origin', ctx.headers.origin);
      ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
   });