Vue中使用axios以及axios的请求封装(以移动端vant为例)
一、项目安装vant
二、执行命令安装axios (npm install axios)
三、封装请求(将以下最终生成的js放在api文件夹下面的axios.js中,文件夹和js都是自己建立的,api的文件夹在src下面))
1、两个方法,一个是请求之前的拦截,一个是响应后的拦截,请求之前的拦截器中可以向里面添加token,请求之后的拦截可以对返回code的值做处理,比如token过期跳转登录等等
// http request拦截器 添加一个请求拦截器 axios.interceptors.request.use(function (config) { let token = window.localStorage.getItem("token") if (token) { //将token放到请求头发送给服务器,将tokenkey放在请求头中 config.headers.token = token; //也可以这种写法 // config.headers['token'] = token; }
return config;
}, function (error) { Toast.fail('请求超时'); // Do something with request error return Promise.reject(error); });
// 添加一个响应拦截器 axios.interceptors.response.use(function (response) { if (response.data && response.data.code) { if (response.data.message === 'token失效' || response.data.message === '请求头中没有token') { //未登录 Toast.fail("登录信息已失效,请重新登录"); router.push('/login'); } if (parseInt(response.data.code) === -1) { Toast.fail("请求失败"); } } return response; }, function (error) { Toast.fail("服务器连接失败"); return Promise.reject(error); })
2、接下来将axios的请求方法封装一下(这里说明一下,vue中会将所有的请求都默认在当前域名下)
let base = ''; //通用方法 export const POST = (url, params) => { const getTimestamp = new Date().getTime(); return axios.post(`${base}${url}?timer=${getTimestamp}`, params).then(res => res.data) } export const GET = (url, params) => { const getTimestamp = new Date().getTime(); return axios.get(`${base}${url}?timer=${getTimestamp}`, { params: params }).then(res => res.data) } export const PUT = (url, params) => { return axios.put(`${base}${url}`, params).then(res => res.data) } export const DELETE = (url, params) => { return axios.delete(`${base}${url}`, { params: params }).then(res => res.data) } export const PATCH = (url, params) => { return axios.patch(`${base}${url}`, params).then(res => res.data) }
3、将以上所有内容整理一下,建立axios.js文件,js完整内容如下
import axios from 'axios' import router from '../router/index' import { Toast } from 'vant'; let token = ''; axios.defaults.withCredentials = false; axios.defaults.headers.common['token'] = token; axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';//配置请求头 // http request拦截器 添加一个请求拦截器 axios.interceptors.request.use(function (config) { let token = window.localStorage.getItem("token") if (token) { //将token放到请求头发送给服务器,将tokenkey放在请求头中 config.headers.token = token; //也可以这种写法 // config.headers['token'] = token; } return config; }, function (error) { Toast.fail('请求超时'); // Do something with request error return Promise.reject(error); }); // 添加一个响应拦截器 axios.interceptors.response.use(function (response) { if (response.data && response.data.code) { if (response.data.message === 'token失效' || response.data.message === '请求头中没有token') { //未登录 Toast.fail("登录信息已失效,请重新登录"); router.push('/login'); } if (parseInt(response.data.code) === -1) { Toast.fail("请求失败"); } } return response; }, function (error) { Toast.fail("服务器连接失败"); return Promise.reject(error); }) let base = ''; //通用方法 export const POST = (url, params) => { const getTimestamp = new Date().getTime(); return axios.post(`${base}${url}?timer=${getTimestamp}`, params).then(res => res.data) } export const GET = (url, params) => { const getTimestamp = new Date().getTime(); return axios.get(`${base}${url}?timer=${getTimestamp}`, { params: params }).then(res => res.data) } export const PUT = (url, params) => { return axios.put(`${base}${url}`, params).then(res => res.data) } export const DELETE = (url, params) => { return axios.delete(`${base}${url}`, { params: params }).then(res => res.data) } export const PATCH = (url, params) => { return axios.patch(`${base}${url}`, params).then(res => res.data) }
三、在main,js中讲以上封装的方法挂载在vue的原型链上,方面后面调用
import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./store"; import "./plugins/vant.js"; import {POST} from './api/axios'; import {GET} from './api/axios'; Vue.prototype.postRequest = POST; Vue.prototype.getRequest = GET; Vue.config.productionTip = false; new Vue({ router, store, render: h => h(App) }).$mount("#app");
四、以上工作完成之后在页面中可这么调用
post请求
this.postRequest(url,param).then(res => {})
get请求
this.getRequest(url,param).then(res => {})