1. 程式人生 > >vue.js 跨域的解決方法(轉載)

vue.js 跨域的解決方法(轉載)

vue專案中,前端與後臺進行資料請求或者提交的時候,如果後臺沒有設定跨域,前端本地除錯程式碼的時候就會報“No 'Access-Control-Allow-Origin' header is present on the requested resource.” 這種跨域錯誤。

要想本地正常的除錯,解決的辦法有三個:

一、後臺更改header

header('Access-Control-Allow-Origin:*');//允許所有來源訪問  
header('Access-Control-Allow-Method:POST,GET');//允許訪問的方式   

這樣就可以跨域請求資料了。

二、使用JQuery提供的jsonp  (注:vue中引入jquery,自行百度)

methods: {  
  getData () {  
    var self = this  
    $.ajax({  
      url: 'http://f.apiplus.cn/bj11x5.json',  
      type: 'GET',  
      dataType: 'JSONP',  
      success: function (res) {  
        self.data = res.data.slice(0, 3)  
        self.opencode = res.data[0].opencode.split(',')  
      }  
    })  
  }  
}  

  

通過這種方法也可以解決跨域的問題。

 

三、使用http-proxy-middleware 代理解決(專案使用vue-cli腳手架搭建)

 

例如請求的url:“http://f.apiplus.cn/bj11x5.json

1、開啟config/index.js,在proxyTable中添寫如下程式碼:

     

proxyTable: {  
  '/api': {  //使用"/api"來代替"http://f.apiplus.c"  
    target: 'http://f.apiplus.cn', //源地址  
    changeOrigin: true, //改變源  
    pathRewrite: {  
      '^/api': 'http://f.apiplus.cn' //路徑重寫  
      }  
  }  
}  

2、使用axios請求資料時直接使用“/api”:

getData () {  
 axios.get('/api/bj11x5.json', function (res) {  
   console.log(res)  
 })  

通過這中方法去解決跨域,打包部署時還按這種方法會出問題。解決方法如下:

let serverUrl = '/api/'  //本地除錯時  
// let serverUrl = 'http://f.apiplus.cn/'  //打包部署上線時  
export default {  
  dataUrl: serverUrl + 'bj11x5.json'  
}  
除錯時定義一個serverUrl來替換我們的“/api”,最後打包時,只需要將“http://www.xxx.com”替換這個“/api”就可以了。