Vue axios 封装 API接口

384 阅读2分钟

「这是我参与2022首次更文挑战的第2天,活动详情查看:2022首次更文挑战」。

什么是 axios?

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

在vue项目当中我们经常会用到后端提供的接口进行联调,

例: this.$axios.get("/api/getList").then((response) => {}) this.$axios.post("/api/login",data).then((response) => {})

当页面越来越多的情况下会重复的去请求 this.$axios.get()... this.$axios.post()... 就显得代码很冗余;那么封装一个 request.js 调用api更具模块性。

安装axios

使用 npm:

$ npm install axios

使用 bower:

$ bower install axios 

使用 cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script> 

引入

在 src 目录下添加 utils 文件夹后创建 request.js

import axios from 'axios'
export function request(config) {
    // 1.创建axios实例
    const instance = axios.create({
        baseURL: 'http://localhost:3001',
        timeout: 5000
    })
    // 2.axios的拦截器
    //  2.1 请求拦截
    instance.interceptors.request.use(config => {
        // 1.比如config中的一些信息不符合服务器的要求
        // 2.比如每次发送网络请求时,都希望在界面中显示一个请求图标
        // 3.某些网络请求(比如登录(token)),必须携带一些特殊的信息
        return config
    }, err => {
        // 请求失败拦截
        //return err
    });
    //  2.2 响应拦截
    instance.interceptors.response.use(res => {
        // 响应成功拦截  可以直接返回res.data
        // // 获取错误信息
        // const errorCode = {
        //     '401': '认证失败,无法访问系统资源',
        //     '403': '当前操作没有权限',
        //     '404': '访问资源不存在',
        //     'default': '系统未知错误,请反馈给管理员'
        // };
        // const msg = errorCode[code] || response.data.msg || errorCode['default'];
        // if (code === 500) {
        //     return Promise.reject(new Error(msg))
        // } else if (code !== 200) {
        //     return Promise.reject('error')
        // }else{
        //     return response.data
        // }
        return res
    }, err => {
        // 响应失败拦截
        //return err
    })
    // 3.发送真正的请求
    //  instance本身是一个promise对象
    return instance(config)
}

在 src 目录下添加 api 文件夹后创建 xxx.js

import request from '@/utils/request' 
// 引入封装的request.js文件
//登录
export function Login(data) {
     return request({
         method: 'post',
         url: '/user/login',        
         data,
     })
 }
//登录
export function getCode(params) {
    return request({
        method: 'get',
        url: '/user',        
        params,
    })
}

使用

import { Login , getCode } from "@/api/api";
export default {
    data() {
        return {
            form: {
                username: 'test2',
                password: 'test2',
                code: '',
            }
        }
    },
    created(){
        this.toLogin();
    }
    methods: {
        toLogin(){
            let data = {
                username: this.form.username,
                password: this.form.password
            };
            Login( data ).then(( response ) => {
                console.log( response );
            });
            refreshCode( {code: this.form.code} ).then(( response ) => {
                console.log( response );
            })
        }
    },
}

结尾

也可以根据自己的项目需求操作。具体操作就仁者见仁智者见智了。 如果更多需求,或者是不一样的需求,可以根据自己的需求进行修改。

一个前端小白,若文章有错误内容,欢迎大佬指点讨论!