當游覽器報這樣的錯時,表示你的請求需要跨域!
這里,我說的是使用webpack+vue-cli+vue-resource中跨域問題,
在config文件下面有index.js文件里有一個叫proxyTable的配置參數
proxyTable: {
'/restful':{
target:'http://xxxxx/member/service/',
changeOrigin:true,
pathRewrite:{//可以不寫
'^/restful':'/restful'
}
}
},
changeOrigin這參數設置為true的時候,就可以虛擬一個本地代理的服務接收請求這樣就可以解決跨域問題了target是你請求接口的域名
接口調用的時候可以這么寫
this.$http.post(commonUrl + "/restful/member?op=getMember&access_token=111", { op: 'getMember', }).then(response => }, response => { }); },
有關於API proxy的說明,使用的就是這個參數。
https://vuejs-templates.github.io/webpack/proxy.html
這個參數主要是一個地址映射表,你可以通過設置將復雜的url簡化,例如我們要請求的地址是api.xxxxxxxx.com/list/1,可以按照如下設置:
proxyTable: {
'/list': {
target: 'http://api.xxxxxxxx.com',
pathRewrite: { //可以不寫
'^/list': '/list'
}
}
}
這樣我們在寫url的時候,只用寫成 /list/1 就可以代表api.xxxxxxxx.com/list/1.
那么又是如何解決跨域問題的呢?其實在上面的'list'的參數里有一個changeOrigin參數,接收一個布爾值,如果設置為true,那么本地會虛擬一個服務端接收你的請求並代你發送該請求,這樣就不會有跨域問題了,當然這只適用於開發環境。增加的代碼如下所示:
proxyTable: {
'/list': {
target: 'http://api.xxxxxxxx.com',
changeOrigin: true,
pathRewrite: {
'^/list': '/list'
}
}
}