axios介绍
axios是基于promise的网络请求库,可以在nodejs和浏览器中运行。在服务端axios使用原生的nodejs的http模块,在客户端浏览器中则而是用xmlhttprequests,本质是对XHR的封装,只不过是promise的实现版本;
功能:
- 从浏览器中创建 XMLHttpRequest
- 从 node.js 中创建 http 请求
- 支持 Promise API
- 拦截请求和响应和转换数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防止 XSRF 攻击
开始封装:
1,新建myAxios.js和backend.js;
myAxios主要是对axios的封装,而backend是对后端状态码的判断;
myAxios.js:
import Axios from 'axios';
import { ErrorToken, GlobalResponseCode, BusinessResponseCode, ApiResult } from '@/api/backend';
import router from '@/router';
const axios = Axios.create({
timeout: 60 * 1000,
headers: { 'Content-Type': 'application/json;charset=UTF-8' },
});
axios.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.authToken = token;
}
return config;
});
axios.interceptors.response.use(
(response) => {
return Promise.resolve(response);
},
(error) => {
Promise.reject(error);
}
);
class MyAxios {
get(url, params) {
console.log('params', params);
return this.request(axios.get(url, params));
}
post(url, data) {
return this.request(axios.post(url, data));
}
put(url) {
return this.request(axios.put(url));
}
async request(axiosRequest) {
try {
const res = await axiosRequest;
if (!res.data || res.data.code != '000000') {
this.resCodePrompt(res.data.code);
console.warn('SeverError', res);
return new ApiResult().setError(res.data);
}
return new ApiResult().setSuccess(res.data);
} catch (error) {
const res = error.response;
this.resErrorPrompt(res);
return new ApiResult().setNetworkError();
}
}
resCodePrompt(resCode) {
if (ErrorToken.includes(resCode)) {
this.$message({ type: 'error', message: '登录凭证无效,请重新登录' });
router.push('/login');
}
const message = GlobalResponseCode[resCode] || BusinessResponseCode[resCode];
if (message) {
return this.$message({ type: 'error', message: '登录凭证无效,请重新登录' });
}
}
resErrorPrompt(res) {
if (!res) {
this.$message({ type: 'error', message: '网络错误!' });
} else if (res.status === 404) {
this.$message({ type: 'error', message: '找不到资源!' });
} else if (res.status === 500) {
this.$message({ type: 'error', message: '内部错误!' });
} else {
this.$message({ type: 'error', message: `${res.status}` });
}
}
}
export const myAxios = new MyAxios();
backend.js
export class ApiResult {
isSuccess = false;
stu = RequestStu.success;
code = '000000';
msg = '';
data = null;
setSuccess(res) {
this.isSuccess = true;
this.stu = RequestStu.success;
this.msg = res.msg;
this.data = res.data;
this.code = res.code;
console.log('this:', this);
return this;
}
setError(res) {
this.stu = RequestStu.error;
this.msg = res.msg;
this.code = res.code;
return this;
}
setNetworkError() {
this.stu = RequestStu.networkError;
return this;
}
}
export const ErrorToken = ['000002', '000003', '000004'];
export const GlobalResponseCode = {
'000000': '成功',
'000001': '请求失败',
'000002': '请重新登录',
'000003': '请重新登录',
'000004': '请重新登录',
'000005': '非法请求',
'000006': '参数非法',
'000007': '数据为空',
};
export const BusinessResponseCode = {
'000101': '账号信息有误,请确认',
'000102': '图片验证码有误',
'000103': '短信验证码错误',
'000104': '手机号有误,请确认',
'000105': '请先勾选保单设计须知。',
'000106': '短信验证码获取频繁',
'000107': '修改失败',
'000108': '添加保单信息失败',
'000109': '保单已存在',
'000110': '内部错误',
'000111': '保单设计已完成',
'000112': '获取图片失败,请刷新重试',
'000113': '图片保存失败,请重试',
'000114': '上传文件过大,请重新上传',
'000115': '文件上传失败,请重新上传',
'000116': '已参加该活动',
'000117': '活动已结束',
'000118': '参加的活动不存在',
};
export const RequestStu = {
success: 'success',
error: 'error',
networkError: 'networkError',
};
2,使用
1,比如有一个登陆接口 ;我们需要封装一下:
import { myAxios } from '../myAxios';
const prefix = '/backend'
export default {
queryLogin(mobileNo) {
return myAxios.get(`${prefix}/api/user/login`, mobileNo);
},
};
2,然后再vue组件中请求这个接口:
methods: {
async handleLogin() {
if (!this.loginForm.account || !this.loginForm.password) {
return this.$message('账号或者密码不能为空!');
}
const { isSuccess, data, code } = await api.login.queryLogin({
account: 'xinjie1',
password: '123456789',
});
if (!isSuccess) {
return this.$message({ type: 'error', message: code });
}
console.log(data)
....
}
}
3,vue配置接口代理,解决开发环境中的跨域问题;vue.config.js配置如下:
const api = 'http://10.11.12.181:26341';
devServer: {
proxy: {
'/backend': {
target: api,
changeOrigin: true,
ws: false,
pathRewrite: { '/api': '' },
},
},
},
4,如果是上传文件,需要使用formData,接口封装需要处理一下:
import { myAxios } from '../myAxios';
const prefix = '/backend'
export default {
uploadImg(policyId, policyNo, file) {
const formData = new FormData();
formData.append('policyId', policyId.toString());
formData.append('policyNo', policyNo);
formData.append('uploadFile', file);
const axiosConfig = {
headers: {
'Content-Type': 'multipart/form-data',
},
timeout: 10000,
transformRequest: [
function (data, headers) {
return data;
},
],
};
return myAxios.post(`${prefix}/api/user/uploadImg`, formData, { axiosConfig: axiosConfig });
},
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)