egg post跨域请求问题
发布于 7 年前 作者 xumjs8623 13914 次浏览 来自 问答

plugin.js

'use strict';

// had enabled by egg
// exports.static = true;
exports.cors = {
  enable: true,
  package: 'egg-cors',
};

config.default.js

'use strict';

module.exports = appInfo => {
  const config = {};
  config.middleware = [ 'test' ];
  // should change to your own
  config.keys = appInfo.name + '_1501029269140_9663';

  // add your config here
  config.security = {
    // csrf: {
    //   ignoreJSON: true, // 默认为 false,当设置为 true 时,将会放过所有 content-type 为 `application/json` 的请求
    // },
    methodnoallow: {
      enable: false
    }, 
    domainWhiteList: [ 'localhost:8080' ]
  };
  return config;
};

router.js

'use strict';

module.exports = app => {
  app.get('/', 'home.index');
  app.get('/home/bannerList', 'home.index');
  app.get('/home/classifyList', 'home.index');
  app.post('/home/productList', 'home.index');
  // app.resources('topics', '/home/productList', 'api');
};

然后get请求是正常的 post请求的options 为什么都没有返回呢 image.png 而且我手动去中间那捕捉options请求,然后返回状态码200,post也不会发起第二次请求了

3 回复

你的 POST header 里都带了什么字段?在 config.cors 设置一下允许的字段 From Noder

domainWhiteList: [ 'http://localhost:8080' ]

改成这样看看。CORS是会验证 协议 + 域名 + 端口

谢谢大家 已经解决了 这里添加了credentials:true 就可以了,我研究研究原因 image.png

回到顶部