溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

vue怎么封裝Axios的get、post請求

發(fā)布時間:2022-06-01 15:09:24 來源:億速云 閱讀:1078 作者:iii 欄目:開發(fā)技術(shù)

這篇“vue怎么封裝Axios的get、post請求”文章的知識點大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“vue怎么封裝Axios的get、post請求”文章吧。

封裝Axios的get、post請求

Axios在vue項目中用的較多,每次都要寫一遍很是不方便,尤其其中的config配置項是公用的,完全可以封裝一下,這樣下次再用就可以直接CV了!畢竟CV大法香??!

1.封裝Axios基礎(chǔ)配置

創(chuàng)建一個request.js 文件,內(nèi)容如下,我把解釋性文字放在注釋里了。

import axios from 'axios'
export function request(config) {
  // 1.創(chuàng)建axios的實例
  const instance = axios.create({
    // 設(shè)置基礎(chǔ)的url配置項,這樣接口處的url前面就不用寫url:'http://127.0.0.1:8000/api/home',直接寫成 url:'/api/home', 就可以了
    baseURL: 'http://127.0.0.1:8000/', 
    //設(shè)置請求超時時間
    timeout: 5000 
  })
  // 2.axios的攔截器,用不到的可以忽略這節(jié)
  // 2.1.請求攔截的作用
  instance.interceptors.request.use(config => {
    return config
  }, err => {
    console.log('請求攔截err: '+err);
  })
  // 2.2.響應(yīng)攔截
  instance.interceptors.response.use(res => {
    return res.data
  }, err => {
        console.log('響應(yīng)攔截err: '+err);
  })
  // 3.發(fā)送真正的網(wǎng)絡(luò)請求
  return instance(config)
}

2.封裝網(wǎng)絡(luò)請求

我們可以將相關(guān)的網(wǎng)絡(luò)請求都放在一個js中,這樣再使用和修改的時候就方便查找了。其中g(shù)et請求比較簡單,post 的請求根據(jù)傳對象輸類型不同,要做不同設(shè)置。

現(xiàn)在來說說post請求常見的數(shù)據(jù)格式(content-type)

Content-Type: application/json : 請求體中的數(shù)據(jù)會以json字符串的形式發(fā)送到后端,這種是axios默認的請求數(shù)據(jù)類型,我們只需將參數(shù)序列化json字符串進行傳遞即可,無需多余的配置。

Content-Type: application/x-www-form-urlencoded:請求體中的數(shù)據(jù)會以普通表單形式(鍵值對)發(fā)送到后端

Content-Type: multipart/form-data: 它會將請求體的數(shù)據(jù)處理為一條消息,以標(biāo)簽為單元,用分隔符分開。既可以上傳鍵值對,也可以上傳文件。

創(chuàng)建一個network.js 文件,內(nèi)容如下:

// 導(dǎo)入封裝好的Axios
import {request} from './request' //注意request.js的相對路徑問題
//1. get請求---獲取首頁的多個數(shù)據(jù)
export function getHomeMultidata() {
  return request({
    url:'/api/home',
    method:'get',
    // 可以帶參數(shù)也可以不帶參數(shù)
    // params: {
    //     userName: 'Lan',
    //     password: '123'
    // }
  })
}
// 2.1 post請求---傳輸json數(shù)據(jù)時,獲取電視劇多個數(shù)據(jù)
export function getTvshowMultidata() {
  return request({
    url:'/api/Tvshow',
     headers: {
      'Content-Type': 'application/json'
    },
    method:'post',
    data: {
        userName: 'Lan',
        password: '123'
     }
  })
}
//2.2 post請求---傳輸文件流,表單Form Data 數(shù)據(jù)時
export function getMovieMultidata() {
  return request({
    url:'/api/Movie',
    headers: {
    'Content-Type': 'multipart/form-data';
    },
    method:'post',
    data: {
        userName: 'Lan',
        password: '123'
     }
  })
}

3.vue中使用

在script 標(biāo)簽中按需導(dǎo)入network.js 中需要使用的方法

import {getHomeMultidata} from "network/home/network"; //導(dǎo)入js,路徑自己根據(jù)文件位置設(shè)置

在方法中按照promise的格式調(diào)用函數(shù)即可 

created() {
      // 在方法中調(diào)用函數(shù)即可
        getHomeMultidata().then(
          res => {
          // 此處res 為返回的數(shù)據(jù),將返回的數(shù)據(jù)進行處理顯示
            this.banners = res.homedata.slice(0,5)
            this.newestData = res.homedata.slice(5,12)
            
        ).catch(
          err => {
            console.log(err)
          }
        );
    },

network中的其他網(wǎng)絡(luò)請求方法使用方法同上。

vue axios兩種方法(封裝和不封裝)get請求和post請求

一.沒有封裝的用法

1.首先在項目中下載axios

npm install axios -s //此方法會將axios下載到package.json中的"dependencies"模塊中,大家可以自行查看

2.因為沒有封裝所以需要在單個vue組件中的編寫js的地方進行引用axios;語法如下

<script>
import axios from  ' axios'
</script>

3.然后在生命周期函數(shù)中進行調(diào)用數(shù)據(jù)

export default{ 
created() {
 
      //get請求    
    axios.get("url", {
 
      params: { //此處為get請求傳遞的參數(shù) 但是一把get請求是沒有參數(shù)的 params是固定的
          password: "123456",
         userName: "320621200305185129",
        },
      })
      
 
     .then(function (response) {
       console.log(response, 666666);
     })
     .catch(function (error) {
        console.log(error, 44444);
      });
      
  },
}
 
//post請求
axios.post('url', {
//此處是參數(shù)
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

每個項目的的接口都是不一樣的,很多時候代碼都不是唯一性的,要靈活的運用

二.封中之后的用法

首先一個目錄utils,在該目錄下創(chuàng)建request.js 在里面編寫

import axios from 'axios'
 
 
export function request(config) {
  // 1.創(chuàng)建axios的實例
  const instance = axios.create({
    // 設(shè)置基礎(chǔ)的url配置項,這樣接口處的url前面就不用寫了
 
    baseURL: 'http://192.168.0.112:9518/', 基礎(chǔ)代碼
    //設(shè)置請求超時時間
    timeout: 5000 
  })
 
  // 2.axios的攔截器,用不到的可以忽略這節(jié)
  // 2.1.請求攔截的作用
  instance.interceptors.request.use(config => {
    return config
  }, err => {
    console.log('請求攔截err: '+err);
  })
 
  // 2.2.響應(yīng)攔截
  instance.interceptors.response.use(res => {
    return res.data
  }, err => {
        console.log('響應(yīng)攔截err: '+err);
  })
 
  // 3.發(fā)送真正的網(wǎng)絡(luò)請求
  return instance(config)
}

然后在目錄下創(chuàng)建api在此處創(chuàng)建index.js  在此處引用上方創(chuàng)建axios實例

import {request} from '../utils/request'
 
//get請求
 
export function denglu() {
  return request({
    url: 'login',
    method: 'get',
    params:{ //此處為傳遞的參數(shù) //get請求一般是不傳遞參數(shù)的
        password:'123456',
        uerName:'5555555555'
    }
    // header: { // 已經(jīng)在request.js里面進行全局設(shè)置,也可以在請求里面局部設(shè)置其他headers
    //    'Content-Type': 'text/plain'
    // }
  })
}
 //post請求
export function denglu() {
  return request({
    url: 'login',
    method: 'post',
    data:{ //此處為傳遞的參數(shù)
        password:'123456',
        uerName:'5555555555'
    }
    // header: { // 已經(jīng)在request.js里面進行全局設(shè)置,也可以在請求里面局部設(shè)置其他headers
    //    'Content-Type': 'text/plain'
    // }
  })
}

然后需要在vue組件的中 在編寫js的地方引入index.js

<script>
import denglu from  "../api/index"
</script>

之后就可以在vue組件方法中進行應(yīng)用了,下面是我在vue組件中根據(jù)上面的代碼進行應(yīng)用的實例 

vue怎么封裝Axios的get、post請求

vue怎么封裝Axios的get、post請求

vue怎么封裝Axios的get、post請求

以上就是關(guān)于“vue怎么封裝Axios的get、post請求”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI