當我們前端用Vue開發項目的時候,涉及到前端和後臺連調真實數據對接會出現很多問題,比如跨域... .我們需要把本地localhost 地址改爲線上訪問接口數據地址域名,
開發環境API代理設置
要配置代理規則,請在config / index.js中編輯dev.proxyTable選項。 dev服務器正在使用http代理中間件進行代理,因此您應參考其文檔以獲取詳細的用法。 但這是一個簡單的例子:
// config/index.js
module.exports = {
// ...
dev: {
proxyTable: {
// proxy all requests starting with /api to jsonplaceholder
'/api': {
target: 'http://test.data.com',
pathRewrite: {
'^/api': ''
}
}
}
}
}
上面的例子將代理請求 /api/posts/1 到 http://test.data.com
那麼又是如何解決跨域問題的呢?其實在上面的'list'
的參數裏有一個changeOrigin
參數,接收一個布爾值,如果設置爲true
,那麼本地會虛擬一個服務端接收你的請求並代你發送該請求,這樣就不會有跨域問題了,當然這隻適用於開發環境。增加的代碼如下所示:
// config/index.js
module.exports = {
// ...
dev: {
proxyTable: {
// proxy all requests starting with /api to jsonplaceholder
'/api': {
target: 'http://test.data.com',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
除了靜態網址之外,您還可以使用glob模式來匹配網址,例如/ API/ **。 有關詳細信息,請參閱上下文匹配。 此外,您可以提供一個過濾器選項,該選項可以是自定義函數,用於確定請求是否應被代理:
proxyTable: {
'*': {
target: 'http://test.data.com',
filter: function (pathname, req) {
return pathname.match('^/api') && req.method === 'GET'
}
}
}
具體可以參考https://vuejs-templates.github.io/webpack/proxy.html