亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

vue3之a(chǎn)xios跨域請求問題及解決

 更新時間:2023年09月26日 09:58:35   作者:fresh_nam  
這篇文章主要介紹了vue3之a(chǎn)xios跨域請求問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

前言

做前后端分離的網(wǎng)頁開發(fā)時,難免會遇到跨域問題,這里解決使用axios請求的跨域問題。

一、版本

1.Vue:3.1.4

2.axios:0.21.1

二、問題

1.使用axios直接請求搜狗的圖片接口

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.瀏覽器會報如下錯誤:

在這里插入圖片描述

三、解決

這時候就需要配置代理了

1.在項目的根目錄添加一個名字為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,
                // 替換掉請求路徑的/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>

這次就不會報錯:

在這里插入圖片描述

注意:

每次更改vue.config.js后都要重啟項目才能生效

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論