vue cli 利用 import axios from “axios”;

接口搭建目录

vue cli api 接口对接搭建插图

api 存放各种接口。utils 对接接口基础搭建 utils 新建request.js

api文件夹 demo js

import request from '@/utils/request'

// 活动列表
export function action_list_api(data) {
    return request({
        url:'/action/list',
        method:'POST',
        data
    })
}

request.js 内容

import axios from "axios";
import { Message } from 'element-ui';
import helper from "@/common/helper";


// create an axios instance
const service = axios.create({
    baseURL:process.env.VUE_APP_API_BASE_URL,
    timeout:'50000',
    headers:{
        'Content-Type': 'application/x-www-form-urlencoded'
    }
})

// 请求拦截器
service.interceptors.request.use(function (config){
    let tokenInfo = helper.get('tokenInfo');
    if(tokenInfo){
        config.headers['usertoken'] = tokenInfo.token
        config.headers['usertokenkey'] = tokenInfo.token_key
    }
    return config;
},function (error){
    return Promise.reject(error)
})
// 响应拦截器

// respone interceptor
service.interceptors.response.use(
    response => {
        const code = response.data.code;
        if (code * 1 == 1000 || code * 1 == 991 || code * 1 == 101) {
            helper.set("tokenInfo", "");
        }
        return response
    },
    error => {
        Message({
            message: '请求失败,请刷新后重新操作',
            center: true,
            customClass: "errorMessage",
            type: "error"
        })
        return Promise.reject(error);
    }
)

export default service

By lxcss

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注