Egg: 跨域问题:Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Created on 23 Jan 2018  ·  12Comments  ·  Source: eggjs/egg

  • Node Version: 9.3.0
  • Egg Version: ^2.0.0
  • Plugin Name: egg-cors
  • Plugin Version: ^2.0.0

环境类似于这个问题

一个 eggJS 容器(api)做 api 服务器,一个 eggJS 容器(admin)做 Vue 后台 SPA 的托管,用 traefik 做反向代理,api 和 admin 在同一个 overlay private 网络中。

现在的问题是,从 admin 发送 post 请求给 api,options 返回 200,post 请求不返回,报错『Failed to load http://api/api/v1/user/signIn: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://admin.localhost' is therefore not allowed access.』

api 的配置为:

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

exports.security = false
// config.default.js
config.cors = {
  origin: '*',
  allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS'
}

试过很多次,都没成功,不知道问题出在哪?谢谢。

尝试的方法包括但不限于给 security 配置里加白名单 ['http://admin.localhost']

image

Most helpful comment

你可以试下在 egg docker 里面自己 curl ip 看看有没有 header,二分法定位下问题到底是 egg 还是中间 proxy

All 12 comments

如果不做安全检查的话,你可以在plugin中设置:
exports.security = false; // 关闭安全检查

提供下 API server 的最小可复现代码库

@atian25 就是一个很简单的 egg 应用,和安全/cors 有关的代码都已经贴出,作为约定大于配置的框架,其他地方没有修改与安全/cors有关的代码,问题贴出来只是让你们帮看下,我已经换用 AWS lambda 了。

我是怀疑你 config 没写对,提供最小可复现代码库才能排查

因为你提供的步骤无法复现

@atian25 不用 docker swarm mode + traefik 只是单独在本地启动跨域没有问题的

那说明不是 egg 的问题,你可以排查下 cors header 有没有正常输出,如果输出了,那 admin 那边有没有接受到,如果没有,那就查下中间的 proxy 是不是有问题咯。

我们本地无法复现,你也给不出可以复现的方式,所以也只能提供思路你自己查了。

@atian25 嗯,谢谢。

你可以试下在 egg docker 里面自己 curl ip 看看有没有 header,二分法定位下问题到底是 egg 还是中间 proxy

@toknT if you are a qualified developer, you must know about CORS, it's a common web scenario.

@toknT if you are a qualified developer, you must know about CORS, it's a common web scenario.
sorry I just mistake config the config file. but I realy don't like the style of configs.

egg-cors is just a standalone plugin, so if you don't like it, you are free to write your own one, it's ok.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Leungkingman picture Leungkingman  ·  3Comments

popomore picture popomore  ·  3Comments

Webjiacheng picture Webjiacheng  ·  3Comments

Quekie picture Quekie  ·  3Comments

Azard picture Azard  ·  3Comments