Access to XMLHttpRequest at 'http://xxxx' from origin 'http://localhost:8080'
has been blocked by CORS policy: Response to preflight request doesn't pass
access control check: No 'Access-Control-Allow-Origin' header is present on
the requested resource.
解決方法(一)
第一步,在后端接受方,對返回的數據添加響應頭,使用下面這句代碼:
// 添加響應頭,解決node返回數據給ajax跨域的不兼容的問題
res.setHeader('Access-Control-Allow-Origin', '*')
第二步,默認情況下,axios將JavaScript對象序列化為JSON,要以application/x-www-form-urlencoded格式發(fā)送數據,可以在請求前端,使用qs庫對數據進行編碼。先npm中安裝qs庫,如果安裝很慢,可以使用淘寶鏡像cnpm install qs --save安裝。
npm install qs --save
然后在使用axios的VUE文件中<script></script>標簽內引用qs庫:
import qs from 'qs'
接下來就可以使用qs.stringify(data)轉換json數據了!
//使用下面qs庫對數據進行編碼
this.$axios.post('http://localhost:3000', qs.stringify({
username: 'user',
password: '123456'
}))
.then((response) => { // 請求成功處理
console.log(response)
//轉換數據為字符串
alert(JSON.stringify(response.data))
// 跳轉路由到主頁面
this.$router.replace('/home')
})
.catch((error) => { // 請求失敗處理
console.log(error)
})
解決方法(二)
可以自己設置一個代理服務器,使用proxyTable 我比較推薦這種方法。
首先在config/index.js 里面找到proxyTable :{} ,然后在里面加入
'/api': {
target: 'http://localhost:8888',// 相當于自帶http://localhost:8888/api
changeOrigin: true,
pathRewrite: {
'^/api': ''// 重定向刪除/api
}
}
注意這里面 /api是你自定義的,寫成什么都可以。
target 設置你調用的接口域名和端口號。
這里理解成用‘^/api’代替target里面的地址,后面組件中我們調接口時直接用api代替 。文章來源:http://www.zghlxwxcb.cn/news/detail-515858.html
比如我要調用’http://localhost:8888/getuser‘,直接寫‘/api/getuser’即可。文章來源地址http://www.zghlxwxcb.cn/news/detail-515858.html
this.$api.('/api/getuser')
.then(res => {
console.log(res)
})
到了這里,關于VUE項目使用axios發(fā)送post跨域請求,返回數據失敗問題的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!