123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- import Vue from "vue";
- import axios from "axios";
- import qs from "qs";
- import user from "@/store/modules/user";
- const instance = axios.create({
- baseURL: process.env.VUE_APP_BASE_API,
- timeout: 5000,
- headers: {
- "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
- },
- transformRequest: [
- data => {
- if (typeof data !== "object") return data;
- let newData: IAny = {};
- Object.keys(data).forEach(key => {
- if ([null, undefined, ""].includes(data[key])) return;
- if (typeof data[key] === "object") {
- data[key] = JSON.stringify(data[key]);
- }
- newData[key] = data[key];
- });
- return qs.stringify(newData);
- }
- ]
- });
- instance.interceptors.response.use(
- x => x,
- err => ({
- data: {
- errno: -1,
- errmsg: "网络请求失败",
- data: err
- }
- })
- );
- const getResult: <T>(x: IBaseResult) => IResult<T> = <T>({
- data,
- errmsg,
- errno
- }: IBaseResult<T>) => {
- if (errno === 0) return [null, data];
- return [{ errno, errmsg }, (data || {}) as T];
- };
- export const post: IRequest = async <T>(url: string, params: any) => {
- const { data } = await instance.post<IBaseResult<T>>(url, params);
- return getResult<T>(data);
- };
- export const get: IRequest = async <T>(url: string, params: any) => {
- const { data } = await instance.get<IBaseResult<T>>(url, { params });
- return getResult<T>(data);
- };
- export const post_auth: IRequest = async <T>(url: string, params: any) =>
- await post<T>(url, Object.assign({}, params, { token: user.Token }));
- export const get_auth: IRequest = async <T>(url: string, params: any) =>
- await get<T>(url, Object.assign({}, params, { token: user.Token }));
- export default {
- install(vue: typeof Vue) {
- Object.assign(vue.prototype, {
- $get: get,
- $post: post,
- $get_auth: get_auth,
- $post_auth: post_auth
- });
- }
- };
|