vue3之a(chǎn)xios跨域請(qǐng)求問題及解決
前言
做前后端分離的網(wǎng)頁開發(fā)時(shí),難免會(huì)遇到跨域問題,這里解決使用axios請(qǐng)求的跨域問題。
一、版本
1.Vue:3.1.4
2.axios:0.21.1
二、問題
1.使用axios直接請(qǐng)求搜狗的圖片接口
https://pic.sogou.com/napi/pc/searchList?mode=1&start=0&xml_len=48&query=美女
<template>
<div class="about">
</div>
</template>
<script>
import axios from 'axios'
export default {
name: "About",
data(){
return {
}
},
created(){
axios.get('https://pic.sogou.com/napi/pc/searchList',{
params:{
mode: 1,
start: 0,
xml_len: 48,
query: '美女'
}}).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
}
}
</script>2.瀏覽器會(huì)報(bào)如下錯(cuò)誤:

三、解決
這時(shí)候就需要配置代理了
1.在項(xiàng)目的根目錄添加一個(gè)名字為vue.config.js的js文件:

2.在該文件里面寫下如下代碼:
module.exports = {
configureWebpack:{
resolve:{
// 給路徑起別名
alias:{
'assets': '@/assets',
'common': '@/common',
'components': '@/components',
'network': '@/network',
'views': '@/views'
}
}
},
devServer:{
proxy:{
'/sougou':{
// 跨域的服務(wù)器地址
target: 'https://pic.sogou.com/napi/pc/searchList',
// 是否允許跨域
changeOrigin: true,
// 替換掉請(qǐng)求路徑的/sougou為“”
pathRewrite:{'^/sougou': ""}
},
}
}
}
}3.使用
<template>
<div class="about">
</div>
</template>
<script>
import axios from 'axios'
export default {
name: "About",
data(){
return {
}
},
created(){
axios.get('/sougou',{
params:{
mode: 1,
start: 0,
xml_len: 48,
query: '美女'
}}).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
}
}
</script>這次就不會(huì)報(bào)錯(cuò):

注意:
每次更改vue.config.js后都要重啟項(xiàng)目才能生效
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue項(xiàng)目Network: unavailable的問題及解決
這篇文章主要介紹了vue項(xiàng)目Network: unavailable的問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
如何在Vue 3中擴(kuò)展Vue Router鏈接詳解
vue-router是Vue.js官方的路由插件,它和vue.js是深度集成的,適合用于構(gòu)建單頁面應(yīng)用,這篇文章主要給大家介紹了關(guān)于如何在Vue 3中擴(kuò)展Vue Router鏈接的相關(guān)資料,需要的朋友可以參考下2021-06-06
區(qū)分vue-router的hash和history模式
這篇文章主要介紹了區(qū)分vue-router的hash和history模式,幫助大家更好的理解和學(xué)習(xí)vue路由,感興趣的朋友可以了解下2020-10-10
vue使用vue-i18n實(shí)現(xiàn)國(guó)際化的實(shí)現(xiàn)代碼
Vue3利用vue-plugin-hiprint插件實(shí)現(xiàn)無預(yù)覽打印功能
vue鼠標(biāo)hover(懸停)改變background-color移入變色問題

