Chr*_*itz 6 proxy vue.js webpack-dev-server vue-resource
我正在尝试使用webpack-dev-server代理配置将api请求发送到外部域,我似乎无法使其正常工作.
这是我的配置:
var path = require('path')
module.exports = {
entry: './client/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'public/assets'),
publicPath: 'assets'
},
devServer: {
contentBase: 'public',
proxy:{
'/api/v1*': {
target: 'http://laravelandwebpack.demo/',
secure: false
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,/api/v1...
只要我的应用程序向uri 发出请求,它就应该发送该请求http://laravelandwebpack.demo
.
在我的Vue应用程序中,我正在使用它vue-resource
来发出请求,并且我使用所需的uri前缀默认所有请求:
var Vue = require('vue')
Vue.use(require('vue-resource'))
new Vue({
el: 'body',
http: {
root: '/api/v1', // prefix all requests with this
headers:{
test: 'testheader'
}
},
ready: function (){
this.$http({
url: 'tasks',
method: 'GET'
}).then(function (response){
console.log(response);
}, function (response){
console.error(response);
})
}
})
Run Code Online (Sandbox Code Playgroud)
URL正在构建正确,但它们仍然指向localhost:8080
哪个是webpack-dev-server:
我阅读并重新阅读webpack-dev-server的文档,我无法弄清楚我在哪里设置错误.有任何想法吗?
小智 1
我找到了该问题的解决方案。就我而言,我需要将请求代理到后端的任何/api/*
路径,因此我绕过任何不以 api 开头的请求。
样本:
proxy: {
'*': {
target: 'http://localhost:8081',
secure: false,
rewrite: function(req) {
console.log('rewriting');
req.url = req.url.replace(/^\/api/, '');
},
bypass: function(req, res, proxyOptions) {
if (req.url.indexOf('api') !== 0) {
console.log('Skipping proxy for browser request.');
return '/index.html';
}else{
return false;
}
}
}
}