ts版axios二次封装

src中创建一个api文件夹,里面有两个文件

request.ts

import axios from "axios";

export const Service = axios.create({

    timeout: 8000, //延迟时间

    method: 'POST',

    headers: {

        "content-Type": "application/x-www-form-urlencoded",

        "pc-token": "4a82b23dbbf3b23fd8aa291076e660ec", //后端提供

    }

})

// 请求拦截

Service.interceptors.request.use(config => {

    return config

})

// 响应拦截

Service.interceptors.response.use(response => {

    return response.data

}, err => {

    console.log(err)

})

index.ts

import {
    Service
} from "./request";
interface searchConfig {
    page: number | string
    mod: string
}
interface getConfig {
    page: number | string
}
// 搜索接口
export function searchCar(config: searchConfig) {
    const params = new URLSearchParams()

    params.append('page', config.page as string);
    params.append('mod', config.mod);

    return Service({
        url: "./api/oldcar/searchCar",
        data: params
    })
}

// 列表接口
export function getCarList(config: getConfig) {
    const params = new URLSearchParams()
    params.append('page', config.page as string)
    return Service({
        url: "/api/oldcar/getCarList",
        data: params
    })
}

你可能感兴趣的:(vue.js,javascript,typescript)