【问题标题】:Proxying webpack dev server in Vue在 Vue 中代理 webpack 开发服务器
【发布时间】:2017-09-12 12:46:43
【问题描述】:

我正在尝试使用vue-axiosvuex 将所有api/ 请求代理到http://localhost:3000。命令行的输出显示代理已创建,但实际上并未代理到正确的地址和 404。

我在 webpack 中有以下设置:

dev: {
  env: require('./dev.env'),
  port: 8080,
  autoOpenBrowser: true,
  assetsSubDirectory: 'static',
  assetsPublicPath: '/',
  proxyTable: {
    'api/': {
      target: 'https://localhost:3000/api',
      changeOrigin: true,
      pathRewrite: {
        '^/api':""
      }
    }
  }
}

在我的动作文件中,我有:

import Vue from 'vue'

export const register = ({ commit }, user) => {
  return new Promise((resolve, reject) => {
    Vue.axios.post('users', user)
        .then(res => {
          console.log(res)
          debugger
        })
        .catch(err => {
          console.error(err)
          debugger
        })
  })
}

控制台输出提示代理已经建立:

[HPM] Proxy created: /api  ->  https://localhost:3000/api
[HPM] Proxy rewrite rule created: "^/api" ~> ""

但是当我实际调用该函数时,它返回http://localhost:8080/users 404 (Not Found)

这有什么不正确的?

我咨询过

这些解决方案均无效。

我听说这可能是 hmr 的问题,但似乎不太可能。

有什么想法吗?

我尝试了以下组合:

  '/api': {
    target: 'https://localhost:3000',
    secure: false,
    changeOrigin: true
  },

  'api/': {
    target: 'https://localhost:3000',
    secure: false,
    changeOrigin: true
  },

  'api/*': {
    target: 'https://localhost:3000',
    secure: false,
    changeOrigin: true
  },

  '*/api/**': {
    target: 'https://localhost:3000',
    secure: false,
    changeOrigin: true
  },

  '*': {
    target: 'https://localhost:3000',
    secure: false,
    changeOrigin: true
  },

  '/api/*': {
    target: 'http://localhost:3000',
    changeOrigin: true
  }

proxy: {
  "/api": {
    "target": {
      "host": "localhost",
      "protocol": 'http:',
      "port": 3000
    },
    ignorePath: true,
    changeOrigin: true,
    secure: false
  }
},

【问题讨论】:

  • 同样的问题,还是没有解决办法

标签: javascript vue.js webpack webpack-dev-server vue-cli


【解决方案1】:

我刚刚遇到了同样的问题并尝试了所有方法。事实证明,代理将匹配的路径段/api 附加到目标的末尾,并在那里查找代理文件。所以这条规则:

'/api/*': {
    target: 'http://localhost:3000',
    changeOrigin: true
}

实际上是在这里寻找文件:

http://localhost:3000/api

不直观。如果您希望它更直观地运行并针对实际目标,则需要从路径中删除匹配的部分,如下所示:

pathRewrite: {'^/api' : ''}

正确的规则变成:

'/api/*': {
    target: 'http://localhost:3000',
    changeOrigin: true,
    pathRewrite: {'^/api' : ''}
}

由于未知原因,pathRewrite 未明确列在文档侧边栏 here 中,尽管它隐藏在配置指南的 1 个位置。

【讨论】:

    【解决方案2】:

    尝试向以下Vue.axios.post("api/users", user) 发出请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      • 2017-10-25
      • 2018-10-23
      • 2021-04-10
      • 1970-01-01
      • 2020-05-04
      • 2016-03-05
      相关资源
      最近更新 更多