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'
}