Vue跨域問題解決方案


前端和后端在不同機器上開發,前端請求后台數據時出現跨域問題

解決方案:

方法一(無效):

1.安裝axios,並在main.js中引用

import axios from 'axios'

Vue.prototype.$axios=axios;

2.在根目錄下創建vue.config.js文件

3.在vue.config.js文件中配置

module.exports = {
  devServer: {
    open: true,
    host: 'localhost',
    port: 8080,
    https: false,
    hotOnly: false,
    proxy: {
      // 配置跨域
      '/api': {
        target: 'http://192.168.1.105:8081',//后端接口地址
        ws: true,
        changOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },
    before: app => {}
  }
};

4.請求數據

this.$axios.get('/api/test')
//最后請求的地址會是http://192.168.1.105:8081/hello,但我測試還是localhost,無效

方法二:

1.安裝axios,並在main.js中引用

import axios from 'axios'

Vue.prototype.$axios=axios;

2.直接配置在config文件下index.js的proxyTable中

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/': {
        target: 'http://192.168.1.105:8081',//后端接口地址
        changOrigin: true,
        pathRewrite: {
          '^/': '/'
        }
      }
    }
  }
}

3.就可以請求到數據了

this.$axios.get('/hello').then(res=>{
            console.log(res);
          })


免責聲明!

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



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