vue-cli项目中axios接口封装以及api的统一管理

一、在src下新建http.js和api.js

接口请求封装:http.js

import axios from 'axios';


const withAxios = apiConfig => {
    // 环境的切换
    if (process.env.NODE_ENV == 'development') {
        axios.defaults.baseURL = 'http://192.168.1.231:9000/admin';}
    else if (process.env.NODE_ENV == 'debug') {
        axios.defaults.baseURL = 'http://192.168.1.231:9000';
    }
    else if (process.env.NODE_ENV == 'production') {
        axios.defaults.baseURL = 'http://192.168.1.231:9000';
    }
    const token = window.localStorage.getItem('token');
    const serviceMap = {};
    apiConfig.map(({ name, url, method }) => {
        serviceMap[name] = async function (data = {}) {
            let key = "";
            if (method === "post" || method === "put") {
                key = "data";
            }
            return axios({
                method,
                url: url,
                [key]: data,
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + token
                },
                dataType: 'json'
            });
        };
    });
    return serviceMap;
};

export default withAxios;

接口api统一封装: api.js

import withAxios from "./http.js";

const apiConfig = [
    {
        name: "login",
        url: "/auth",
        method: "post"
    },
    {
        name: "userList",
        url: "/user/listPage?page=1&size=10",
        method: "get"
    },
];

export default withAxios(apiConfig);

引入和定义方式:main.js中

import http from 'http.js'
import ports from 'ports'
 Vue.prototype.http = http
 Vue.prototype.ports = ports

使用 方式:组件内

this.http.post(this.ports.manage.login, {
                    userAccount: 'test',
                    userPassword: '111111',
                    cert: '1111111111'
                }, res => {
                    if (res.success) {
                       // 返回正确的处理
                    } else {
                      // 返回错误的处理 
                    }
                })

接口请求只添加了一个token,具体的还需要自己设置一下。

你可能感兴趣的:(vue-cli项目中axios接口封装以及api的统一管理)