egg icon indicating copy to clipboard operation
egg copied to clipboard

egg-cors配置跨域无效

Open xiang-fish opened this issue 8 years ago • 20 comments

Node Version: v8.10.0 Egg Version: 2.2.1 Plugin Name: egg-cors Plugin Version: 2.2.1 Platform: windows

config.default.js config.security = { domainWhiteList: ['http://10.240.5.48:8080'] }

config.cors = { origin: '*', allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH' }

plugin.js

exports.cors ={ enable: true, package: 'egg-cros }

error Access to XMLHttpRequest at 'http://localhost:7001/client/_0PEgqZ5hNE49vQrAAAA?timeStamp=1541389963780' from origin 'http://10.240.5.48:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

xiang-fish avatar Nov 05 '18 04:11 xiang-fish

koa2-cros 用这个吧

fxh615 avatar Nov 06 '18 08:11 fxh615

错误不都写着很清楚了么

The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

image

whxaxes avatar Nov 06 '18 08:11 whxaxes

如果你要用 origin: '*' 又想带 withCredentials,配置改成这样

config.cors = {
  credentials: true,
  origin: ctx => ctx.get('origin'),
}

如果只想让 domainWhiteList 的可以跨域,那就不用配置 origin

whxaxes avatar Nov 06 '18 08:11 whxaxes

@whxaxes 我服务器A通过nginx代理到服务器B(egg server),且在A服务器配置了跨域相关,但缺产生了跨域问题?这个让我很疑惑,如果使用了egg-cors就会出现两次跨域的配置,如果不用egg-cors就无法获取到服务器A设置的跨域配置

lyh2668 avatar Nov 07 '18 03:11 lyh2668

@lyh2668 没看懂你的问题,能给个 repo 加以描述么

whxaxes avatar Nov 07 '18 05:11 whxaxes

@whxaxes 问题解决了,JAVA的Tomcat服务应该是会对OPTIONS做204处理的,egg似乎不会做相关操作,所以我在nginx里面对options强制返回204即可

lyh2668 avatar Nov 07 '18 06:11 lyh2668

@lyh2668 会处理 OPTIONS 的( https://github.com/koajs/cors/blob/master/index.js#L127 ),你是没有配置 domainWhiteList 吧,所以你的跨域请求的 OPTIONS 被拦了

whxaxes avatar Nov 07 '18 07:11 whxaxes

@whxaxes 我觉得method options的处理不应该放在domainWhiteList里来处理 下面的逻辑有问题吧,allowMethods明显少了OPTIONS

const defaults = {
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH',
}

if (options.allowMethods) {
    ctx.set('Access-Control-Allow-Methods', options.allowMethods);
}

lyh2668 avatar Nov 07 '18 08:11 lyh2668

当然domainWhiteList我也有配置过的

lyh2668 avatar Nov 07 '18 08:11 lyh2668

@lyh2668

下面的逻辑有问题吧,allowMethods 明显少了 OPTIONS

allowMethod 是用来配置允许跨域的请求方法,会设置到 Access-Control-Allow-Methods 这个响应头上 ,而设置这个 allowMethod 的时候正是 OPTIONS 请求的时候,也就是 OPTIONS 是跨域请求前必备的询问请求,所以是不可能给用户配置的。( 有兴趣可以看一下实现:https://github.com/koajs/cors/blob/master/index.js#L116 )

我觉得 method options 的处理不应该放在 domainWhiteList 里来处理

没有在 domainWhiteList 中处理,只是 egg-cors 会根据用户有没有配置 origin ,如果没有配置 origin ,则根据 domainWhiteList 来判断给不给这个请求跨域。如果有配置 origin ,那么就不会用到 domainWhiteList ( 有兴趣可以看一下实现: https://github.com/eggjs/egg-cors/blob/master/app.js#L8 )

当然 domainWhiteList 我也有配置过的

如果你觉得你配置对了,还是不行,能否给个能复现的 repo ,我帮你看看?

whxaxes avatar Nov 08 '18 09:11 whxaxes

#3177

thonatos avatar Nov 08 '18 09:11 thonatos

没一个靠谱的回答

gb-6k-house avatar Jan 11 '19 02:01 gb-6k-house

如果你要用 origin: '*' 又想带 withCredentials,配置改成这样

config.cors = {
  credentials: true,
  origin: ctx => ctx.get('origin'),
}

如果只想让 domainWhiteList 的可以跨域,那就不用配置 origin

这个有效。mark一下。

hinkey avatar Mar 11 '19 04:03 hinkey

egg-cors内部使用了@koa/cors的代码 @koa/cors的配置代码

/**

  • CORS middleware *
  • @param {Object} [options]
    • {String|Function(ctx)} origin Access-Control-Allow-Origin, default is request Origin header
    • {String|Array} allowMethods Access-Control-Allow-Methods, default is 'GET,HEAD,PUT,POST,DELETE,PATCH'
    • {String|Array} exposeHeaders Access-Control-Expose-Headers
    • {String|Array} allowHeaders Access-Control-Allow-Headers
    • {String|Number} maxAge Access-Control-Max-Age in seconds
    • {Boolean} credentials Access-Control-Allow-Credentials
    • {Boolean} keepHeadersOnError Add set headers to err.header if an error is thrown
  • @return {Function} cors middleware
  • @api public */

不写就万事大吉

lirunkai avatar Jan 05 '20 10:01 lirunkai

@lyh2668 会处理 OPTIONS 的( https://github.com/koajs/cors/blob/master/index.js#L127 ),你是没有配置 domainWhiteList 吧,所以你的跨域请求的 OPTIONS 被拦了

我这边的问题是,在@lyh2668 的情形下。增加了domainWhiteList,options请求通过了,但是同时set了一个domain在header。nginx又返回*。又有header contains multiple values的问题,请问怎么处理呢?

bigbossx avatar Mar 17 '20 08:03 bigbossx

踩了很久的坑终于解决了 贴一下我的配置

config.security = { csrf: { enable: false, ignoreJSON: true }, domainWhiteList: [ '*'] };

config.cors = { credentials: true, withCredentials: true, allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH', };

指定了 domainWhiteList 之后 ,config.cors就不要写 origin了。两个同时写的话,我这边会出现 The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed

carrykingdow avatar Dec 22 '21 02:12 carrykingdow

为啥我加了之后我的options预检请求直接挂掉了呢?Access-Control-Request-Headers这个我也设置好了

zhaoqi-nb avatar Dec 31 '21 08:12 zhaoqi-nb

@carrykingdow

zhaoqi-nb avatar Dec 31 '21 08:12 zhaoqi-nb

为什么我开启了 cors 在响应头没有 Allow 这些响应头 PS: tegg 中不能用 koa2-cors, 替换为 egg-cors 好了

mookilyu avatar Jun 08 '24 14:06 mookilyu

config.default.ts

import { Context, EggAppConfig, EggAppInfo, PowerPartial } from "egg";

export default (appInfo: EggAppInfo) => {
  const config = {
    security: {
      domainWhiteList: ["http://localhost:3000"],
      csrf: {
        bodyName: "sToken",
        cookieName: "csrfToken",
      },
    },
    cors: {
      withCredentials: true,
      credentials: true,
      origin: (ctx: Context) => ctx.get("origin"),
    },
  } as PowerPartial<EggAppConfig>;

  // override config from framework / plugin
  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + "_1717341580304_6025";

  // add your egg config in here
  config.middleware = [];

  // add your special config in here
  const bizConfig = {
    sourceUrl: `https://github.com/eggjs/examples/tree/master/${appInfo.name}`,
  };

  // the return config will combines to EggAppConfig
  return {
    ...config,
    ...bizConfig,
  };
};

plugin.js

import { EggPlugin } from "egg";

const plugin: EggPlugin = {
  // mysql: {
  //   enable: true,
  //   package: "egg-mysql",
  // },
  cors: {
    enable: true,
    package: "egg-cors",
  },
  tegg: {
    enable: true,
    package: "@eggjs/tegg-plugin",
  },
  teggConfig: {
    enable: true,
    package: "@eggjs/tegg-config",
  },
  teggController: {
    enable: true,
    package: "@eggjs/tegg-controller-plugin",
  },
  teggSchedule: {
    enable: true,
    package: "@eggjs/tegg-schedule-plugin",
  },
  eventbusModule: {
    enable: true,
    package: "@eggjs/tegg-eventbus-plugin",
  },
  aopModule: {
    enable: true,
    package: "@eggjs/tegg-aop-plugin",
  },
  tracer: {
    enable: true,
    package: "egg-tracer",
  },
};

export default plugin;

在开发 yarn dev 跨域成功, 但是在 yarn start 跨域失败

mookilyu avatar Jun 11 '24 14:06 mookilyu