vue跨域解決方法
vue項(xiàng)目中,前端與后臺進(jìn)行數(shù)據(jù)請求或者提交的時候,如果后臺沒有設(shè)置跨域,前端本地調(diào)試代碼的時候就會報“No 'Access-Control-Allow-Origin' header is present on the requested resource.” 這種跨域錯誤。

要想本地正常的調(diào)試,解決的辦法有三個:
一、后臺更改header
header('Access-Control-Allow-Origin:*');//允許所有來源訪問
header('Access-Control-Allow-Method:POST,GET');//允許訪問的方式
這樣就可以跨域請求數(shù)據(jù)了。
二、使用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 代理解決(項(xiàng)目使用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請求數(shù)據(jù)時直接使用“/api”:
getData () {
axios.get('/api/bj11x5.json', function (res) {
console.log(res)
})
通過這中方法去解決跨域,打包部署時還按這種方法會出問題。解決方法如下:
let serverUrl = '/api/' //本地調(diào)試時
// let serverUrl = 'http://f.apiplus.cn/' //打包部署上線時
export default {
dataUrl: serverUrl + 'bj11x5.json'
}
總結(jié)
以上所述是小編給大家介紹的vue跨域解決方法 ,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!
相關(guān)文章
解決Vue的項(xiàng)目使用Element ui 走馬燈無法實(shí)現(xiàn)的問題
這篇文章主要介紹了解決Vue的項(xiàng)目使用Element ui 走馬燈無法實(shí)現(xiàn)的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
vue將后臺數(shù)據(jù)時間戳轉(zhuǎn)換成日期格式
這篇文章主要為大家詳細(xì)介紹了vue將后臺數(shù)據(jù)時間戳轉(zhuǎn)換成日期格式,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07

