search
HomeWeb Front-endVue.jsHow vue3 solves the axios request encapsulation problem

vue3 actual axios request encapsulation problem

1. Create an http folder in the src directory, and create index.js, request.js, and api.js under the http folder

2. The role of index.js: used to export all interfaces defined by api.js, the code is as follows

export * from './api';

3. The request.js code is as follows:

import axios from 'axios';
import buildURL from 'axios/lib/helpers/buildURL';
import { merge } from 'axios/lib/utils';

//判断指定参数是否是一个纯粹的对象,所谓"纯粹的对象",就是该对象是通过"{}"或"new Object"创建的
function isPlainObject (val) {
      return val && val.constructor.name === 'Object'
}

//请求之前进行拦截,可做的操作:1、添加loading的加载;2、添加请求头;3、判断表单提交还是json提交
let requestInterceptors = [
    config => {
        //添加loading的加载
        
        //添加请求头
        config.headers.authorization = sessionStorage.getItem('Token');
        //判断表单提交还是json提交
        if (config.emulateJSON && isPlainObject(config.data)) {
            config.data = buildURL('', config.data).substr(1);
        }
        return config;
    }
]

//请求响应之后进行拦截,可做操作:1、取消loading的加载;2、对返回状态进行判断:如请求错误、请求超时、获取数据失败、暂无数据等等
let responseInterceptors = [
    res => {
        //取消loading加载
        
        //对返回状态进行判断:如请求错误、请求超时、获取数据失败等等

        //返回结果
        return Promise.resolve(res);
    },
    err => {
        //取消loading加载
        
        //对返回状态进行判断:如请求错误、请求超时、获取数据失败等等

        //返回结果
        return Promise.reject(err);
    }
]

//组装请求
let serviceCreate = config => {
    let service = axios.create(merge({}, config));
    service.interceptors.request.use(...requestInterceptors);
    service.interceptors.response.use(...responseInterceptors);
    return service
}
serviceCreate();
export { serviceCreate, merge };

4. the api.js code is as follows :

import { serviceCreate, merge } from '@/http/request';

//这种方式可以采用单个项目的接口,也可以使用多个项目的接口,看自己的项目情况而定
let http0 = serviceCreate({
    baseURL: '/project1/api1',
    timeout: 15000,//请求超时
    emulateJSON: true,//默认表单提交
})
let http1 = serviceCreate({
    baseURL: '/project2/api2',
    timeout: 15000,//请求超时
    emulateJSON: true,//默认表单提交
})

//get请求示例
export function getData(params, config) {
    return http0.get('/project/list', merge(config, { params }));
}
//delete请求示例
export function deleteData(params, config) {
    return http0.delete('/project/list', merge(config,{ params }));
}
//post请求示例(表单提交)
export function postDataFrom(params, config) {
    return http0.post('/project/list', params, config);
}
//post请求示例(json提交)
export function postDataJson(params, config) {
    return http0.post('/project/list', params, merge(config, { emulateJSON: false }));
}
//put请求示例(表单提交)
export function putDataFrom(params, config) {
    return http0.put('/project/list', params, config);
}
//put请求示例(json提交)
export function putDataJson(params, config) {
    return http0.put('/project/list', params, merge(config, { emulateJSON: false }));
}

5. Call in the page

import { getData, deleteData, postDataFrom, postDataJson, putDataFrom, putDataJson } from "@/http";

getData({ name: "我是参数" }).then(res => { console.log("返回数据", res) })
deleteData({ name: "我是参数" }).then(res => { console.log("返回数据", res) })
postDataFrom({ name: "我是参数" }).then(res => { console.log("返回数据", res) })
postDataJson({ name: "我是参数" }).then(res => { console.log("返回数据", res) })
putDataFrom({ name: "我是参数" }).then(res => { console.log("返回数据", res) })
putDataJson ({ name: "我是参数" }).then(res => { console.log("返回数据", res) })

vue3 axios simple encapsulation tutorial

First create a new utils folder in the root directory, and create two new files below, requests .js and html.js

requests.js is used to introduce axios and set the root domain name and some default settings, interceptors, etc.

import axios from "axios";

const service = axios.create({
    baseURL: 'http://localhost:3000',
    timeout: 10000,
})

// 请求拦截器
service.interceptors.request.use(config=>{
    return config
},err=>{
    return Promise.reject(err)  //返回错误
})
    
// 响应拦截器
service.interceptors.response.use(res=>{
    return res
},err=>{
    return Promise.reject(err)  //返回错误
})


export default service

After writing, expose the created instance object and introduce it in html.js

The function of the html.js file is to call the instance object of requests and all access Store it in this file (api) and import it as needed when using it.

import request from "./requests";
export const GetPosts = () => request.get('posts/1')
export const GetsearchData = (params) => request.get('/list',{params})
export const PostPosts = (params) => request.post('posts',params)

Introduced files:

<template>
    <el-button type="primary" @click="clickGet">点我发送get请求</el-button>
    <el-button type="primary" @click="clickPost">点我发送post请求</el-button>
    <el-button type="primary" @click="clickPut">点我发送put请求</el-button>
    <el-button type="primary" @click="clickDel">点我发送delete请求</el-button>
</template>

<script>
import { GetPosts, PostPosts } from "../../utils/html"

export default {
    setup(){
        function clickGet(){
            GetPosts().then(res => {
                console.log(res)
            })
            // axios({
            //     method: &#39;GET&#39;,
            //     url: &#39;http://localhost:3000/posts&#39;
            // }).then(res => {
            //     console.log(res)
            // })
        }
        function clickPost(){
            PostPosts({
                title: &#39;我超级喜欢打游戏&#39;,
                author: &#39;账本儿erer&#39;,
                age: &#39;24&#39;
            }).then(res => {
                console.log(res)
            })
        }
        function clickPut(){
            
        }
        function clickDel(){
            
        }
        return {
            clickDel,
            clickGet,
            clickPost,
            clickPut
        }
    }
}
</script>

<style>

</style>

The above is the detailed content of How vue3 solves the axios request encapsulation problem. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
分享两个可以绘制 Flowable 流程图的Vue前端库分享两个可以绘制 Flowable 流程图的Vue前端库Sep 07, 2022 pm 07:59 PM

前端有没有现成的库,可以直接用来绘制 Flowable 流程图的?下面本篇文章就跟小伙伴们介绍一下这两个可以绘制 Flowable 流程图的前端库。

vue是前端css框架吗vue是前端css框架吗Aug 26, 2022 pm 07:37 PM

vue不是前端css框架,而是前端JavaScript框架。Vue是一套用于构建用户界面的渐进式JS框架,是基于MVVM设计模式的前端框架,且专注于View层。Vue.js的优点:1、体积小;2、基于虚拟DOM,有更高的运行效率;3、双向数据绑定,让开发者不用再去操作DOM对象,把更多的精力投入到业务逻辑上;4、生态丰富、学习成本低。

聊聊Vue3+qrcodejs如何生成二维码并添加文字描述聊聊Vue3+qrcodejs如何生成二维码并添加文字描述Aug 02, 2022 pm 09:19 PM

Vue3如何更好地使用qrcodejs生成二维码并添加文字描述?下面本篇文章给大家介绍一下Vue3+qrcodejs生成二维码并添加文字描述,希望对大家有所帮助。

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

一文深入详解Vue路由:vue-router一文深入详解Vue路由:vue-routerSep 01, 2022 pm 07:43 PM

本篇文章带大家详解Vue全家桶中的Vue-Router,了解一下路由的相关知识,希望对大家有所帮助!

手把手带你使用Vue开发一个五子棋小游戏!手把手带你使用Vue开发一个五子棋小游戏!Jun 22, 2022 pm 03:44 PM

本篇文章带大家利用Vue基础语法来写一个五子棋小游戏,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

手把手带你了解VUE响应式原理手把手带你了解VUE响应式原理Aug 26, 2022 pm 08:41 PM

本篇文章我们来了解 Vue2.X 响应式原理,然后我们来实现一个 vue 响应式原理(写的内容简单)实现步骤和注释写的很清晰,大家有兴趣可以耐心观看,希望对大家有所帮助!

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software