【问题标题】:Configure webpack proxy for http requests in VueJs + Axios在 VueJs + Axios 中为 http 请求配置 webpack 代理
【发布时间】:2024-05-16 15:45:02
【问题描述】:

我正在使用 Axios 创建一个简单的 VueJs 应用程序来发出 http 请求。像这样的:

load () {
  let vm = this
  this.$http
    .get('/api/posts')
    .then(response => {
      // success
    })
    .catch(error => {
      // failure
    })
}

而在 webpack 配置文件中,config/index.js:

module.exports = {
dev: {
 proxyTable: {
  '/api': {
    target: 'http://jsonplaceholder.typicode.com',
    secure: false,
    changeOrigin: true,
    pathRewrite: { '^/api': '' }
  }
},
}

是否缺少任何东西来完成这项工作?根据这个documentation,webpack 使用http-proxy-middleware,但我不确定它是否已经以某种方式内置在 vue-cli 项目生成中,或者我们需要手动安装它。生成的模板和任何教程都没有提到这一点。

非常感谢。

【问题讨论】:

  • 你使用的是什么版本的 vue-cli? 2 还是 3(测试版)?
  • 最新,2.9.3

标签: webpack vue.js proxy


【解决方案1】:

您的proxyTable 配置本身没有问题。但是……

仔细检查您的 config/index.js 文件。如果您将proxyTable sn-p 添加到具有默认内容的配置文件中,您的config/index.js 文件将是:

module.exports = {
  dev: {
    proxyTable: {                                          // the snippet you added
      '/api': {                                            // the snippet you added
        target: 'http://jsonplaceholder.typicode.com',     // the snippet you added
        secure: false,                                     // the snippet you added
        changeOrigin: true,                                // the snippet you added
        pathRewrite: { '^/api': '' }                       // the snippet you added
      }                                                    // the snippet you added
    },                                                     // the snippet you added

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {},                  // <================================ oops...

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    ...

现在,请注意那里有一个 proxyTable: {}, 属性。它正在覆盖您的配置。

解决方法:删除proxyTable: {},

【讨论】:

  • 好吧,实际上我所做的是填充已经存在的proxyTable: {},正如您所指出的,所以情况不应该如此。
  • 检查是否没有其他proxyTable。或者也许发布你的整个配置文件,因为在 sn-p 没有问题(刚刚测试过)。