我正在尝试使用 vue-axios
和 vuex 将所有
。命令行上的输出表明代理已经创建,但它实际上并没有代理到正确的地址和 404。api/
请求代理到 http://localhost:3000
我在 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)
这有什么不对的地方?
我咨询过
计算器:Proxy requests to a separate backend server with vue-cli
Github 问题:https://github.com/webpack/webpack-dev-server/issues/458
这些解决方案均无效。
我听说这可能是 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/