vue-cli 3.0之跨域請求代理配置及axios路徑配置


vue-cli 3.0之跨域請求代理配置及axios路徑配置

問題:在前后端分離的跨域請求中,報跨域問題

配置:

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/.控制台顯示請求的地址為:http://localhost:8080/api/postData/。

生產環境:

只需要將 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/

 

 

轉載自:https://www.cnblogs.com/cckui/p/10331432.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM