javascript - 在 Vue 中代理 webpack 开发服务器

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

我正在尝试使用 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':""
      }
    }
  }
}

在我的 Action 文件中我有:

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
  }
},

最佳答案

我刚刚遇到了同样的问题并尝试了所有方法。事实证明,代理将匹配的路径段 /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 个位置。

关于javascript - 在 Vue 中代理 webpack 开发服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43442352/

相关文章:

成功提交 Web 表单后,Javascript 重置功能将不起作用

javascript - vue 两个计算属性相互依赖

javascript - ReactJS 文件结构

javascript - NightwatchJS "freezes"

javascript - 将数据从服务器发送到 js 文件.. 获取 Passport 以在 Google map 信息框上显示 Facebook 图像

javascript - 如何使用 chessboard.js 分析模式撤消和重做国际象棋移动

javascript - Vue,使用其名称作为字符串调用方法

javascript - Vue.js 合并数据而不重新渲染?

typescript - 如何将 leaflet-routing-machine 包含到 angular 2 typescript webpack 应用程序中

css - style.css 中的错误模块解析失败 : Unexpected token (2:20) You may need an appropriate loader