vue-cli配置axios,并基于axios进行后台请求函数封装
文章https://www.cnblogs.com/XHappyness/p/7677153.html已经对axios配置进行了说明,后台请求时可直接this.$axios直接进行。这里的缺点是后端请求会散乱在各个组件中,导致复用和维护艰难。
升级:将请求封装在一个文件中并加上类型声明
步骤:
1. npm install axios --save
2. src/common下建server.ts 内容如下
/** * 后台请求设置 */ import axios from 'axios' // import {Notification} from 'element-ui' import { serverUrl } from './configByEnv.js' axios.defaults.withCredentials = true; axios.defaults.baseURL = serverUrl; axios.interceptors.request.use(function (config) { return config; }, function (error) { return Promise.reject(error) }) axios.interceptors.response.use(function (response) { return response.data; }, function (error) { if (error.response.status === 401) { alert(401); // Notification({ // title: '权限无效', // message: '您的用户信息已经失效, 请重新登录', // type: 'warning', // offset: 48 // }); // window.location.href = '/#/login' } else { alert('请求错误'); // Notification({ // title: '请求错误', // message: `${error.response.status} ${error.config.url}`, // type: 'error', // offset: 48, // }) } return Promise.reject(error) }) /** * 后台请求函数 */ class Server implements Server.IServer { // 所有请求函数写在这里 login_async(curSlnId: Server.loginUser): Promise<string[]> { return axios.get(`/login/${curSlnId}`).then((res: any) => res) } } export default new Server()
3. src/types下建server.d.ts,加入server的类型声明
declare namespace Server { // 本文件自己用的不用加export export interface loginUser { name: string, psd: string } export interface IServer { login_async(loginUser: loginUser): Promise<string[]>; } }