欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3之a(chǎn)xios跨域請(qǐng)求問(wèn)題及解決

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

前言

做前后端分離的網(wǎng)頁(yè)開(kāi)發(fā)時(shí),難免會(huì)遇到跨域問(wèn)題,這里解決使用axios請(qǐng)求的跨域問(wèn)題。

一、版本

1.Vue:3.1.4

2.axios:0.21.1

二、問(wèn)題

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.在該文件里面寫(xiě)下如下代碼:

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)文章

最新評(píng)論