vue-cli 3.0 axios 跨域請求代理配置及生產環境 baseUrl 配置

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 中:vue

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 做以下修改:ios

axios.defaults.timeout = 5000 // 請求超時
axios.defaults.baseURL = 'http://api.demourl.com/'

頁面中 axios 請求地址的寫法不變:axios

axios.post('/postData/', {
    name: 'cedric', 
}).then((res) => {
  console.log(res.data)
})

實際請求地址爲:http://api.demourl.com/postData/api

相關文章
相關標籤/搜索