【问题标题】:Nuxt: Set origin on all Axios requests, depending on currenct domainNuxt:根据当前域设置所有 Axios 请求的来源
【发布时间】:2021-12-17 03:51:14
【问题描述】:

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

nuxt.config.js

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

但是,我想让原点动态化 - 所以它取决于当前域。所以我从 nuxt.config.js 中删除了标题,而是创建了这个插件。只是为了测试我已经硬编码了与 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 日志告诉我需要设置原点,但这就是我所做的,对吧?我唯一的想法是:因为这是一个代理请求,所以标头不会以某种方式传输。

更新

我是服务器端渲染,插件在nuxt.config.js中添加如下:

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

【问题讨论】:

  • 你在做任何服务器端渲染吗?每当您执行 axios 请求时,插件都不会运行...您在哪里调用插件,何时调用插件?
  • @mahatmanich 我已经更新了问题
  • 为什么要用onRequest函数而不是直接把headers给axios呢?

标签: vue.js proxy axios nuxt.js


【解决方案1】:

终于明白了。

我删除了插件,而是在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')
    }
  },
}
// ...

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2021-07-02
    • 2019-11-13
    • 2011-09-05
    • 2020-07-18
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    相关资源
    最近更新 更多