怎么查网站备案号,常用免费ppt模板,某某公司电子商务网站建设与维护,网站申请收录1 简介
通过Axios的请求拦截器和响应拦截器实现登录拦截#xff0c;参数封装。 注意#xff1a;前提是你的vue已经安装了Axios。 附安装代码#xff1a;
npm install axios 2 封装代码
2.1 utils文件夹下创建 request.js
// 网络请求方法
import axios from axios
impor…1 简介
通过Axios的请求拦截器和响应拦截器实现登录拦截参数封装。 注意前提是你的vue已经安装了Axios。 附安装代码
npm install axios 2 封装代码
2.1 utils文件夹下创建 request.js
// 网络请求方法
import axios from axios
import router from /router// 自定义axios对象 ajax对象就是axios
const ajax axios.create({baseURL: http://请求IP地址:端口/api, // 服务器基地址headers: {Content-Type: application/json; charsetutf-8},timeout: 10000
})// 添加请求拦截器判断token是否过期
// 请求拦截器
// 设置axios请求头加入token
ajax.interceptors.request.use(config {// 判断是否有token是否已经登录不是请求token,就对请求添加tokenif (localStorage.getItem(token) config.url ! admin/auth/token) {//在请求头加入token名字要和后端接收请求头的token名字一样config.headers.authorization localStorage.getItem(token)}// 根据请求方法自动选择传递参数的方式// get delete 传递params参数// postputpatch 传递data参数if (config.method post || config.method put || config.method patch) {config.data config.params}return config},error {return Promise.reject(error)})// 响应拦截器
ajax.interceptors.response.use(response {// 判断是否登录成功if (response.data.code 0) {console.log(response.data.msg || 请求出错,稍后重试)}return response.data},error {// Token过期请求响应 401 时用户手动获取token强制跳转登录页面if (error.response error.response.status 401) {//清除tokenlocalStorage.removeItem(token)console.log(登录失效请重新登录)//跳转router.push(/login)} else {console.log(服务器连接异常)}return Promise.reject(error)})export default ajax // 导出一个axios函数
2.2 api文件夹下创建index.js 请求的统一出口。
// 登录为例获取token获取账户信息
import {recommendToken, authInfo} from ./loginexport default {recommendToken,authInfo
}2.3 api文件夹下创建login.js 存放所有的登录请求
// 封装发起的请求
import request from /utils/request// 封装网络请求方法
export const recommendToken params request({url: admin/auth/token,method: POST,params
})export const authInfo param request({url: admin/auth/AuthInfo,method: GET,param
})3 使用
api.recommendToken({userName: this.username,password: this.password
}).then(res {// 请求数据处理const token res.data.accessToken// 存储tokenlocalStorage.setItem(token, Bearer token)// 跳转到首页this.$router.push(/)
}).catch(error {// 错误捕获console.log(服务器错误 error.message)
}).finally(() {})api.authInfo().then(res {// 请求完成后逻辑……
}).catch(error {// 错误捕获console.log(error)
})