1. 開發環境跨域配置
在 vue.config.js 文件中:
module.exports = {
runtimeCompiler: true,
publicPath: '/', // 設置打包文件相對路徑
devServer: {
// open: process.platform === 'darwin',
// host: 'localhost',
port: 8071,
// open: true, //配置自動啟動瀏覽器
proxy: {
'/api': {
target: 'http://127.0.0.1:8100/', //對應自己的接口
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api': ''
}
}
}
},
}
注意,配置完成后要重啟服務
配置 axios 請求的 baseUrl
在 main.js 中:
axios.defaults.timeout = 5000 // 請求超時
axios.defaults.baseURL = '/api/' // api 即上面 vue.config.js 中配置的地址
頁面中發送請求:
axios.post('/postData/', {
name: 'cedric',
}).then((res) => {
console.log(res.data)
})
此時,雖然發送的請求到地址:http://localhost:8080/api/postData/, 但是已經代理到了地址: http://127.0.0.1:8100/postData/
2. 生產環境 api 請求接口 baseUrl 配置
只需要將 main.js 中 axios 作如下修改:
axios.defaults.timeout = 5000 // 請求超時
axios.defaults.baseURL = 'http://api.demourl.com/'
頁面中 axios 請求地址的寫法不變:
axios.post('/postData/', {
name: 'cedric',
}).then((res) => {
console.log(res.data)
})
實際請求地址為:http://api.demourl.com/postData/