vue3实战-axios请求封装问题,get、post、put、delete

vue3实战axios请求封装问题

1、在src目录下创建http文件夹,在http文件夹下分别创建index.js、request.js、api.js

2、index.js的作用:用于导出api.js定义的所有接口,代码如下

export * from './api';

3、request.js代码如下:

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、api.js代码如下:

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、页面中调用

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简易封装教程

首先在根目录下新建utils文件夹,并在下面新建两个文件,requests.js和html.js

requests.js用于引入axios并设置根域名以及一些默认设置、拦截器等。

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

写完之后将创建的实例对象暴露出去,在html.js中进行引入

html.js文件的作用是调用requests的实例对象,并将所有的访问均存放在这个文件中(api),使用的时候按需引入即可。

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)

引入的文件:

<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: 'GET',
            //     url: 'http://localhost:3000/posts'
            // }).then(res => {
            //     console.log(res)
            // })
        }
        function clickPost(){
            PostPosts({
                title: '我超级喜欢打游戏',
                author: '账本儿erer',
                age: '24'
            }).then(res => {
                console.log(res)
            })
        }
        function clickPut(){
            
        }
        function clickDel(){
            
        }
        return {
            clickDel,
            clickGet,
            clickPost,
            clickPut
        }
    }
}
</script>

<style>

</style>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文地址:https://blog.csdn.net/yyxy_gis/article/details/124289062