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

關(guān)于axios配置多個(gè)請求地址(打包后可通過配置文件修改)

 更新時(shí)間:2022年09月08日 14:50:33   作者:莫爾道嘎老范  
這篇文章主要介紹了關(guān)于axios配置多個(gè)請求地址(打包后可通過配置文件修改),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

axios配置多個(gè)請求地址(打包后可通過配置文件修改)

開發(fā)過程中可能會(huì)遇到后端接口分布在多個(gè)地址下的情況,

這樣調(diào)用不同接口時(shí),就需要切換不同的請求地址;

我是這樣處理的

核心代碼

// 2.請求攔截器
service.interceptors.request.use(
    (config) => {
        console.log('config', config);
        //發(fā)請求前做的一些處理,數(shù)據(jù)轉(zhuǎn)化,配置請求頭,設(shè)置token,設(shè)置loading等,根據(jù)需求去添加
        config.data = JSON.stringify(config.data); //數(shù)據(jù)轉(zhuǎn)化,也可以使用qs轉(zhuǎn)換
        config.headers = {
            'Content-Type': 'application/x-www-form-urlencoded', //配置請求頭
            // 'Content-Type':'multipart/form-data; boundary=ZnGpDtePMx0KrHh_G0X99Yef9r8JZsRJSXC'
        };
        switch (config.urlType) {
            case 'api1':
                config.url = baseURL + config.url;
                break;
            case 'api2':
                config.url = baseURL2 + config.url;
                break;
            default:
                config.url = baseURL + config.url;
        }
        //注意使用token的時(shí)候需要引入cookie方法或者用本地localStorage等方法,推薦js-cookie
        // const token = getCookie('名稱');//這里取token之前,你肯定需要先拿到token,存一下
        // if(token){
        //   config.params = {'token':token} //如果要求攜帶在參數(shù)中
        //   config.headers.token= token; //如果要求攜帶在請求頭中
        // }
        return config;
    },
    (error) => {
        Promise.reject(error);
    },
);

在axios實(shí)例service中,通過判斷傳入?yún)?shù)的字段來更改url地址

以get請求為例

在這里插入圖片描述

在這里插入圖片描述

完整代碼

axios實(shí)例:

/****   request.js   ****/
// 導(dǎo)入axios
import axios from 'axios';
// 使用element-ui Message做消息提醒
import { ElMessage } from 'element-plus';
let baseURL = configUrl.Base_Resource_URL; //index.html引入的
let baseURL2 = configUrl.Base_Resource_URL2;
//1. 創(chuàng)建新的axios實(shí)例,
const service = axios.create({
    // 超時(shí)時(shí)間 單位是ms,這里設(shè)置了3s的超時(shí)時(shí)間
    timeout: 3 * 1000,
});
// 2.請求攔截器
service.interceptors.request.use(
    (config) => {
        console.log('config', config);
        //發(fā)請求前做的一些處理,數(shù)據(jù)轉(zhuǎn)化,配置請求頭,設(shè)置token,設(shè)置loading等,根據(jù)需求去添加
        config.data = JSON.stringify(config.data); //數(shù)據(jù)轉(zhuǎn)化,也可以使用qs轉(zhuǎn)換
        config.headers = {
            'Content-Type': 'application/x-www-form-urlencoded', //配置請求頭
            // 'Content-Type':'multipart/form-data; boundary=ZnGpDtePMx0KrHh_G0X99Yef9r8JZsRJSXC'
        };
        switch (config.urlType) {
            case 'api1':
                config.url = baseURL + config.url;
                break;
            case 'api2':
                config.url = baseURL2 + config.url;
                break;
            default:
                config.url = baseURL + config.url;
        }
        //注意使用token的時(shí)候需要引入cookie方法或者用本地localStorage等方法,推薦js-cookie
        // const token = getCookie('名稱');//這里取token之前,你肯定需要先拿到token,存一下
        // if(token){
        //   config.params = {'token':token} //如果要求攜帶在參數(shù)中
        //   config.headers.token= token; //如果要求攜帶在請求頭中
        // }
        return config;
    },
    (error) => {
        Promise.reject(error);
    },
);
// 3.響應(yīng)攔截器
service.interceptors.response.use(
    (response) => {
        //接收到響應(yīng)數(shù)據(jù)并成功后的一些共有的處理,關(guān)閉loading等
        return response;
    },
    (error) => {
        /***** 接收到異常響應(yīng)的處理開始 *****/
        if (error && error.response) {
            // 1.公共錯(cuò)誤處理
            // 2.根據(jù)響應(yīng)碼具體處理
            switch (error.response.status) {
                case 400:
                    error.message = error.response.data.msg;
                    break;
                case 401:
                    error.message = '未授權(quán),請重新登錄';
                    break;
                case 403:
                    error.message = '拒絕訪問';
                    break;
                case 404:
                    error.message = '請求錯(cuò)誤,未找到該資源';
                    window.location.href = '/';
                    break;
                case 405:
                    error.message = '請求方法未允許';
                    break;
                case 408:
                    error.message = '請求超時(shí)';
                    break;
                case 500:
                    error.message = '服務(wù)器端出錯(cuò)';
                    break;
                case 501:
                    error.message = '網(wǎng)絡(luò)未實(shí)現(xiàn)';
                    break;
                case 502:
                    error.message = '網(wǎng)絡(luò)錯(cuò)誤';
                    break;
                case 503:
                    error.message = '服務(wù)不可用';
                    break;
                case 504:
                    error.message = '網(wǎng)絡(luò)超時(shí)';
                    break;
                case 505:
                    error.message = 'http版本不支持該請求';
                    break;
                default:
                    error.message = `連接錯(cuò)誤${error.response.status}`;
            }
        } else {
            // 超時(shí)處理
            if (JSON.stringify(error).includes('timeout')) {
                ElMessage.error('服務(wù)器響應(yīng)超時(shí),請刷新當(dāng)前頁');
            }
            error.message = '連接服務(wù)器失敗';
        }
        ElMessage.error(error.message);
        /***** 處理結(jié)束 *****/
        //如果不需要錯(cuò)誤處理,以上的處理過程都可省略
        return Promise.resolve(error.response);
    },
);
//4.導(dǎo)入文件
export default service;

分別封裝請求方式:

/*
 * @Author: 老范
 * @Date: 2022-01-12 15:56:04
 * @LastEditors: 老范
 * @LastEditTime: 2022-01-19 11:52:42
 * @Description: 請?zhí)顚懞喗?
 */
/****   http.js   ****/
// 導(dǎo)入封裝好的axios實(shí)例
import request from './request';
const http = {
    /**
     * methods: 請求
     * @param url 請求地址
     * @param params 請求參數(shù)
     */
    get(url, params, type) {
        const config = {
            method: 'get',
            url: url,
            urlType: type,
        };
        if (params) {
            config.params = params;
        }
        return request(config);
    },
    post(url, params, type) {
        const config = {
            method: 'post',
            url: url,
            urlType: type,
        };
        if (params) config.data = params;
        return request(config);
    },
    put(url, params, type) {
        const config = {
            method: 'put',
            url: url,
            urlType: type,
        };
        if (params) config.data = params;
        return request(config);
    },
    delete(url, params, type) {
        const config = {
            method: 'delete',
            url: url,
            urlType: type,
        };
        if (params) config.params = params;
        return request(config);
    },
};
//導(dǎo)出
export default http;

具體接口例子:

/*
 * @Author: 老范
 * @Date: 2022-01-12 16:17:22
 * @LastEditors: 老范
 * @LastEditTime: 2022-01-19 11:53:39
 * @Description: 請?zhí)顚懞喗?
 */
import http from '../utils/http';
let model = '/api/model/';
// get請求
//根據(jù)ID獲得單個(gè)模型信息
export function getModelParams() {
    return http.get(`/api/getModelList`, {}, 'api2'); //使用第二個(gè)地址
}
// post請求
// 獲取模型集列表
export function getModelViewListAPI(params) {
    return http.post(`/api/modelView/search`, params, 'api1');
}

這樣在封裝接口函數(shù)時(shí)即可控制其請求地址,并且由于地址是由靜態(tài)文件引入的,所以打包后的資源中依然有原文件,可通過該文件更改地址

在這里插入圖片描述

在這里插入圖片描述

axios請求方法

axios中各種方法調(diào)用接口

Axios是一個(gè)基于promise的HTTP庫,可以用在瀏覽器和node.js中

可以提供以下服務(wù):

1、從瀏覽器中創(chuàng)建XMLHttpRequests

2、從node.js創(chuàng)建http請求

3、支持PromiseAPI

4、攔截請求和響應(yīng)

5、轉(zhuǎn)換請求數(shù)據(jù)和響應(yīng)數(shù)據(jù)

6、取消請求

7、自動(dòng)轉(zhuǎn)換JSON數(shù)據(jù)

8、客戶端支持防御XSRF

  • get:獲取數(shù)據(jù)
  • post:提交數(shù)據(jù)(表單提交+文件上傳)
  • put:更新數(shù)據(jù)(所有數(shù)據(jù)推送到后端)
  • patch:更新數(shù)據(jù)(只將修改的數(shù)據(jù)推送到后端)
  • delete:刪除數(shù)據(jù)

get方法

1.不帶參數(shù)

axios.get(“/user”)

2.帶參數(shù)

axios.get("/user",{
?? ?params:{
?? ??? ?id:10,
?? ??? ?age:10
?? ?}
}//請求的地址實(shí)際為 localhost:8080/user?id=10&age=10

注意這里是以對象的形式傳參

簡單的提一句所有的方法也可以這樣寫不過一般習(xí)慣于簡寫

axios({ methods: 'get', url: '/user' })//也就是直接axios({methods:請求方式,url:'路徑',params:{有就帶沒有就不帶}})

post方法

主要提交表單數(shù)據(jù)和上傳文件

axios.post("/user",
?? ?params:{
?? ??? ?id:id
?? ?}
)

注意這里以鍵值對的方式提交params就是鍵名,此處的params也可以省略,直接填寫后面要傳入的參數(shù)

delete方法

1.參數(shù)為普通的字符

axios.delete("/user",{
?? ?params:{
?? ??? ?id:id
?? ?}
})

2.參數(shù)為數(shù)組形式這里比較容易入坑

axios.delete("/user",{
?? ?data:arr
})//其中arr=[1,2,3]的數(shù)組形式存在,鍵值必須是data

put方法

和post方法一樣

axios.put("/user", data);

總結(jié):以上方法中,get方式和delete方法帶參數(shù)時(shí)比較特殊;但最為特殊的時(shí)delete方法帶的參數(shù)為數(shù)組形式時(shí)。

axios.all請求多個(gè)請求

axios.all([getUserAccount(), getUserPermissions()])
? .then(axios.spread(function (acct, perms) {
? }));

最下面來個(gè)常用格式

axios.get('/getUser?id=12345')
? .then(function (response) {
? ? console.log(response)
? ? this.setState({
? ? ? // ...
? ? })
? })
? .catch(function (error) {
? ? // handle error
? ? console.log(error);
? })
axios.get('/getUser', {
? ? params: { // 這里的參數(shù)設(shè)置為URL參數(shù)(根據(jù)URL攜帶參數(shù))
? ? ? id: 12345
? ? }
? })
? .then(function (response) {
? ? console.log(response);
? })
? .catch(function (error) {
? ? console.log(error);
? })?
?
async function getUser() {
? try {
? ? const response = await axios.get('/getUser?id=12345');
? ? console.log(response);
? } catch (error) {
? ? console.error(error);
? }
}

axios全局配置

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

axios的單一實(shí)例化配置

const instance = axios.create({
? baseURL: 'https://api.example.com'
});
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

axios攔截器的使用

可以使用axios攔截器來在發(fā)送請求之前或在響應(yīng)response之前(then方法)來攔截請求并進(jìn)行自定義的設(shè)置,定義request和response攔截器示例如下

axios.interceptors.request.use(function (config) {
? ? return config;
? }, function (error) {
? ? return Promise.reject(error);
? });
?
axios.interceptors.response.use(function (response) {
? ? return response;
? }, function (error) {
? ? return Promise.reject(error);
? })

刪除攔截器的時(shí)候

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

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

相關(guān)文章

  • elementplus?card?懸浮菜單的實(shí)現(xiàn)

    elementplus?card?懸浮菜單的實(shí)現(xiàn)

    本文主要介紹了elementplus?card?懸浮菜單的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07
  • Vue數(shù)據(jù)回顯表單無法編輯的解決方案

    Vue數(shù)據(jù)回顯表單無法編輯的解決方案

    這篇文章主要介紹了Vue數(shù)據(jù)回顯表單無法編輯的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • vue 綁定使用 touchstart touchmove touchend解析

    vue 綁定使用 touchstart touchmove touchend解析

    這篇文章主要介紹了vue 綁定使用 touchstart touchmove touchend解析,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • 深入理解vue中的slot與slot-scope

    深入理解vue中的slot與slot-scope

    這篇文章主要介紹了vue中的slot與slot-scope的相關(guān)知識(shí),非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-04-04
  • vue項(xiàng)目如何監(jiān)聽localStorage或sessionStorage的變化

    vue項(xiàng)目如何監(jiān)聽localStorage或sessionStorage的變化

    這篇文章主要介紹了vue 項(xiàng)目如何監(jiān)聽localStorage或sessionStorage的變化,幫助大家更好的理解和使用vue框架,感興趣的朋友可以了解下
    2021-01-01
  • vue項(xiàng)目出現(xiàn)頁面空白的解決方案

    vue項(xiàng)目出現(xiàn)頁面空白的解決方案

    今天小編就為大家分享一篇vue項(xiàng)目出現(xiàn)頁面空白的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-10-10
  • vue如何給頁面增加url前綴

    vue如何給頁面增加url前綴

    這篇文章主要介紹了vue如何給頁面增加url前綴問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • vue3前端獲取文件的絕對路徑問題解決

    vue3前端獲取文件的絕對路徑問題解決

    這篇文章主要給大家介紹了關(guān)于vue3前端獲取文件的絕對路徑問題解決的相關(guān)資料,文中通過代碼示例介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-09-09
  • vue如何禁止打開調(diào)試模式方法

    vue如何禁止打開調(diào)試模式方法

    這篇文章主要介紹了vue如何禁止打開調(diào)試模式方法,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • vue3中$refs的基本使用方法

    vue3中$refs的基本使用方法

    在Vue中一般很少會(huì)用到直接操作DOM,但不可避免有時(shí)候需要用到,這時(shí)我們可以通過ref和$refs這兩個(gè)來實(shí)現(xiàn),下面這篇文章主要給大家介紹了關(guān)于vue3中$refs的基本使用方法,需要的朋友可以參考下
    2022-03-03

最新評論