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

vue3中封裝Axios請(qǐng)求及在組件中使用詳解

 更新時(shí)間:2023年04月24日 10:25:13   作者:辣椒炒肉-  
目前前端最流行的網(wǎng)絡(luò)請(qǐng)求庫(kù)還是axios,所以對(duì)axios的封裝很有必要,下面這篇文章主要給大家介紹了關(guān)于vue3中封裝Axios請(qǐng)求及在組件中使用的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下

前言

 這篇文章直接能夠在項(xiàng)目中使用,沒(méi)有解釋什么東西,直接復(fù)制粘貼,嘎嘎用。

一、創(chuàng)建文件夾存放封裝好的js

我是創(chuàng)建在src/request/axios.js

二、封裝代碼如下

直接將下面代碼復(fù)制在request.js中,封裝了get,post請(qǐng)求,需要自己配置的是:自己的請(qǐng)求地址,tokenKey是否為token,改為自己存入本地的token名,可以看一下代碼中的注釋,很好看懂。

/**axios封裝
 * 請(qǐng)求攔截、相應(yīng)攔截、錯(cuò)誤統(tǒng)一處理
 */
import axios from 'axios';
import QS from 'qs';
import router from '../router/index'
//qs.stringify()是將對(duì)象 序列化成URL的形式,以&進(jìn)行拼接
//  let protocol = window.location.protocol; //協(xié)議
//  let host = window.location.host; //主機(jī)
//  axios.defaults.baseURL = protocol + "http://" + host;
axios.defaults.baseURL = 'http://localhost:8888'
 
axios.interceptors.request.use( //響應(yīng)攔截
        async config => {
            // 每次發(fā)送請(qǐng)求之前判斷vuex中是否存在token        
            // 如果存在,則統(tǒng)一在http請(qǐng)求的header都加上token,這樣后臺(tái)根據(jù)token判斷你的登錄情況
            // 即使本地存在token,也有可能token是過(guò)期的,所以在響應(yīng)攔截器中要對(duì)返回狀態(tài)進(jìn)行判斷 
            config.headers.token = sessionStorage.getItem('token')
            return config;
        },
        error => {
            return Promise.error(error);
        })
    // 響應(yīng)攔截器
axios.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return Promise.resolve(response); //進(jìn)行中        
        } else {
            return Promise.reject(response); //失敗       
        }
    },
    // 服務(wù)器狀態(tài)碼不是200的情況    
    error => {
        if (error.response.status) {
            switch (error.response.status) {
                // 401: 未登錄                
                // 未登錄則跳轉(zhuǎn)登錄頁(yè)面,并攜帶當(dāng)前頁(yè)面的路徑                
                // 在登錄成功后返回當(dāng)前頁(yè)面,這一步需要在登錄頁(yè)操作。                
                case 401:
                    break
                    // 403 token過(guò)期                
                    // 登錄過(guò)期對(duì)用戶進(jìn)行提示                
                    // 清除本地token和清空vuex中token對(duì)象                
                    // 跳轉(zhuǎn)登錄頁(yè)面                
                case 403:
                    sessionStorage.clear()
                    router.push('/login')
                    break
                    // 404請(qǐng)求不存在                
                case 404:
                    break;
                    // 其他錯(cuò)誤,直接拋出錯(cuò)誤提示                
                default:
            }
            return Promise.reject(error.response);
        }
    }
);
/** 
 * get方法,對(duì)應(yīng)get請(qǐng)求 
 * @param {String} url [請(qǐng)求的url地址] 
 * @param {Object} params [請(qǐng)求時(shí)攜帶的參數(shù)] 
 */
const $get = (url, params) => {
        return new Promise((resolve, reject) => {
            axios.get(url, {
                    params: params,
                })
                .then(res => {
                    resolve(res.data);
                })
                .catch(err => {
                    reject(err.data)
                })
        });
    }
    /** 
     * post方法,對(duì)應(yīng)post請(qǐng)求 
     * @param {String} url [請(qǐng)求的url地址] 
     * @param {Object} params [請(qǐng)求時(shí)攜帶的參數(shù)] 
     */
const $post = (url, params) => {
        return new Promise((resolve, reject) => {
            axios.post(url, QS.stringify(params)) //是將對(duì)象 序列化成URL的形式,以&進(jìn)行拼接   
                .then(res => {
                    resolve(res.data);
                })
                .catch(err => {
                    reject(err.data)
                })
        });
    }
    //下面是vue3必須加的,vue2不需要,只需要暴露出去get,post方法就可以
export default {
    install: (app) => {
        app.config.globalProperties['$get'] = $get;
        app.config.globalProperties['$post'] = $post;
        app.config.globalProperties['$axios'] = axios;
    }
}

三、配置

在main.js中,引入我們第一步封裝的js,然后use()

//引入封裝Axios請(qǐng)求
import Axios from './request/axios';
 
const app = createApp(App).use(VueAxios, axios).use(ElementPlus).use(router).use(Axios)

四、在需要的組件中使用

重點(diǎn)來(lái)了,封裝完了,歸根到底我得用。在組件中導(dǎo)入getCurrentInstance。加上如下代碼。

import {  getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();
  function logout(){
    proxy.$post("/sysStaff/logout",{}).then((response)=>{
      console.log(response)
      if(response.code == 200){
        sessionStorage.clear();
        router.push('/')
        ElMessage({
          message: '退出成功',
          type: 'success',
        })
      }
    })
  }

調(diào)用的時(shí)候,當(dāng)中有兩個(gè)參數(shù),第一個(gè)參數(shù)是路徑,第二個(gè)參數(shù)是個(gè)對(duì)象,里面可以寫要發(fā)送請(qǐng)求的參數(shù),比如:username:shuaibi,password:123456。

補(bǔ)充:通過(guò)具體配置解決跨域問(wèn)題CORS

安裝第三方包webpack-dev-server

不安裝沒(méi)有devServer配置項(xiàng),必須安裝

npm install webpack-dev-server

在根目錄vue.config.js中寫入如下配置

module.exports = {
  // 關(guān)閉語(yǔ)法檢查
  lintOnSave: false,
  // 解決axios發(fā)送請(qǐng)求時(shí)的跨域問(wèn)題,不做配置會(huì)報(bào)錯(cuò)如下↓↓↓↓
  // ccess to XMLHttpRequest at 'http://127.0.0.1:23456/webPage/home_notice.post' 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.
  devServer: {
    // https: false,
    proxy: {
      //  /api 表示攔截以/api開頭的請(qǐng)求路徑
      "/webPage": {
        target: "http://127.0.0.1:23456/", // 跨域的域名(不需要重寫路徑)
        ws: false, // 是否開啟websockede
        changeOrigin: true, // 是否開啟跨域
        // pathRewrite: {
        //   "^/webPage": "",
        // },
      },
    },
  },
};

瀏覽器從一個(gè)域名的網(wǎng)頁(yè)去請(qǐng)求另一個(gè)域名的資源時(shí),域名、端口、協(xié)議任一不同,都是跨域。這里不具體解釋,想了解的可以查資料。

  1. devServer配置項(xiàng)可以開啟一個(gè)反向代理,來(lái)解決跨域問(wèn)題。之前所有的地址拼接可以得到
    /webPage/cooperater.post…最終發(fā)起請(qǐng)求時(shí),如果沒(méi)有寫pathRewrite則表示查找/webPage并在其前拼接target中的地址。最會(huì)向http://127.0.0.1:23456/webPage/cooperater.post口發(fā)起請(qǐng)求。
  2. pathRewrite: {"^/webPage": "***",},表示路由重寫將/webPage替換為***

總結(jié)

vue項(xiàng)目當(dāng)中對(duì)axios請(qǐng)求的封裝就是如此,非常的容易?。?!

到此這篇關(guān)于vue3中封裝Axios請(qǐng)求及在組件中使用的文章就介紹到這了,更多相關(guān)vue3封裝Axios請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論