I am trying to proxy all api/
requests to http://localhost:3000
using vue-axios
and vuex
. The output on the command line says that the proxy has been created but then it doesn't actually proxy to the right address and 404's.
I have the following setup inside of webpack:
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'api/': {
target: 'https://localhost:3000/api',
changeOrigin: true,
pathRewrite: {
'^/api':""
}
}
}
}
And inside of my actions file I have:
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
})
})
}
The console output suggests that the proxy has been established:
[HPM] Proxy created: /api -> https://localhost:3000/api
[HPM] Proxy rewrite rule created: "^/api" ~> ""
But when I actually call the function, it returns http://localhost:8080/users 404 (Not Found)
What is incorrect about this?
I have consulted
Stackoverflow: Proxy requests to a separate backend server with vue-cli
Vue docs: https://vuejs-templates.github.io/webpack/proxy.html
Github issues: https://github.com/webpack/webpack-dev-server/issues/458
None of those solutions worked.
I have heard this might be a problem with hmr but that doesn't seem likely.
Any ideas?
I have tried the following combinations:
'/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
}
},
I just had this same problem and tried everything. It turns out the proxy appends the matched path segment /api
onto the end of the target and looks there for the proxied file. So this rule:
'/api/*': {
target: 'http://localhost:3000',
changeOrigin: true
}
is actually seeking for the file here:
http://localhost:3000/api
Non-intuitive. If you want this to function more intuitively and target the actual target, you need to remove the matched portion from the path like this:
pathRewrite: {'^/api' : ''}
The correct rule becomes:
'/api/*': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {'^/api' : ''}
}
For unknown reason, pathRewrite
is not explicitly listed in the docs sidebar here, though it is tucked away in 1 location in the config guide.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With