>  기사  >  웹 프론트엔드  >  vue3이 Axios 요청 캡슐화 문제를 해결하는 방법

vue3이 Axios 요청 캡슐화 문제를 해결하는 방법

王林
王林앞으로
2023-05-22 21:34:041106검색

Vue3 실제 Axios 요청 캡슐화 문제

1. src 디렉터리에 http 폴더를 만들고, http 폴더 아래에 index.js, request.js, api.js를 각각 만듭니다

2. 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 파일의 기능은 요청의 인스턴스 객체를 호출하고 모든 액세스를 이 파일(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: &#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>

위 내용은 vue3이 Axios 요청 캡슐화 문제를 해결하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제