egg icon indicating copy to clipboard operation
egg copied to clipboard

能否提供一个跨域的示例?

Open zuiidea opened this issue 9 years ago • 14 comments

文档和Issues都查询过了,并没有成功

//config.default.js

module.exports = (appInfo) => {
  return {
    keys: `${appInfo.name}_1489132676072_319`,
    security: {
      domainWhiteList: ['http://localhost:8001'],
      methodnoallow: {
        enable: false,
      },
      xframe: {
        enable: false,
      },
      csrf: {
        enable: false,
        headerName: 'x-csrf-token',
        ignoreJSON: false,
      },
    },
  }
}

//plugin.js

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

zuiidea avatar Apr 07 '17 03:04 zuiidea

cors要打开

jtyjty99999 avatar Apr 07 '17 03:04 jtyjty99999

@jtyjty99999 打开之后发送请求,会产生两次请求,其中一个是OPTIONS的,另一个POST的请求返回404,当然不跨域的情况下是200

zuiidea avatar Apr 07 '17 03:04 zuiidea

@zuiidea 能提交一个demo我看下吗

jtyjty99999 avatar Apr 07 '17 03:04 jtyjty99999

@zuiidea 你发给我的demo,有个地方配置的不正确

domainWhiteList: ['http://localhost:8001', 'http://www.xiaoyaoji.com.cn'] 这里 白名单不要带http 我测试通过了,你也可以测试一下。

配置: domainWhiteList: ['http://localhost:8001', 'http://www.xiaoyaoji.com.cn','www.w3school.com.cn'], 测试地址 http://www.w3school.com.cn/tiy/t.asp?f=jquery_ajax_post

jtyjty99999 avatar Apr 07 '17 06:04 jtyjty99999

@jtyjty99999 是不是可以做下检测或者自动干掉前缀?

atian25 avatar Apr 07 '17 06:04 atian25

整理一下,使用egg做cors跨域的步骤:

  • 配置 egg-security 的 domainWhiteList 为允许跨域的域名

  • ~~关掉 egg-security 的 methodnoallow 中间件 : methodnoallow: { enable: false, },~~

  • 开启 cors插件

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

jtyjty99999 avatar Apr 07 '17 06:04 jtyjty99999

第二步貌似 https://github.com/eggjs/egg-cors 这里没有,补一个吧

atian25 avatar Apr 07 '17 06:04 atian25

@jtyjty99999 是不是可以做下检测或者自动干掉前缀?

@atian25 需要修改下 egg-security 的逻辑, @shaoshuai0102 这个你觉得呢

jtyjty99999 avatar Apr 07 '17 06:04 jtyjty99999

@atian25 我又翻了下源码,不需要关掉了,cors的中间件在最前面处理了

jtyjty99999 avatar Apr 07 '17 06:04 jtyjty99999

@jtyjty99999 ok,thanks

zuiidea avatar Apr 07 '17 06:04 zuiidea

在cors里面开启credential熟悉并且设置为true就好了 config.cors = { origin:'http://ip:port', credentials: true, allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH' };

oneWalker avatar Aug 23 '19 14:08 oneWalker

大佬们可以帮我看看还要配置什么吗,一直都存在跨域问题 config/config.default.js config.security = { csrf: { enable: false, ignoreJSON: true, }, //白名单 domainWhiteList: ['127.0.0.1:8080'], }; //配置跨域 config.cors = { origin: 'http:127.0.0.1:8080', // 匹配规则 域名+端口 *则为全匹配 allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH', credentials: true };

config/plugin.js cors: { enable: true, package: "egg-cors" }

htt828 avatar Mar 12 '20 08:03 htt828

middleware 层面可以处理或者打开吗?serverless无法修改配置文件

stalker-silence avatar Feb 23 '22 03:02 stalker-silence

config.cors = { credentials: true, // 允许任何跨域,若只允许个别IP跨域,则:origin:['http://localhost:8080'] origin: "*", // 被允许的请求方式 allowMethods: "GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS", };

huihuicn avatar Feb 24 '22 08:02 huihuicn