Nuxt:根据当前域在所有 Axios 请求上设置来源

Nuxt: Set origin on all Axios requests, depending on currenct domain

我正在使用 @nuxtjs/proxy 发出代理请求。这是在 nuxt.config.js 中设置的并且工作正常。

nuxt.config.js

proxy: {
  '/api/': {
    target: 'api.example.com',
    headers: {
      'origin': 'www.example.com',
      // ...
    },
    pathRewrite: {
      '^/api/': ''
    }
  },
}
// ...

但是,我想让原点动态化 - 所以它取决于当前域。所以我从 nuxt.config.js 中删除了 header 并创建了这个插件。只是为了测试我硬编码了与 nuxt.config.js

中相同的来源

plugins/origin.js

export default function (ctx) {    
  ctx.$axios.onRequest(config => {
    config.headers['origin'] = 'www.example.com';
    return config;
  }, err => console.log(err));
}

这行不通。 API 日志告诉我需要设置原点,但我就是这么做的,对吧?我唯一的想法是:因为这是代理请求,所以 header 不会以某种方式传输。

更新

我是服务器端渲染,插件是这样添加到nuxt.config.js中的:

plugins: [
  '~/plugins/origin.js'
]

终于想通了。

我删除了插件,而是在 nuxt.config.js

中添加了 onProxyReq 方法
proxy: {
  '/api/': {
    target: 'api.example.com',
    headers: {
      'origin': 'www.example.com',
      // ...
    },
    pathRewrite: {
      '^/api/': ''
    },
    onProxyReq: (proxyReq, req, res) => {
      proxyReq.setHeader('origin', 'www.example.com')
    }
  },
}
// ...