当前位置: 首页 > news >正文

Axios 封装网络请求

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; charset=utf-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参数// post,put,patch 传递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 './login'export 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)
})
http://www.lryc.cn/news/444319.html

相关文章:

  • LeetCode 面试经典150题 190.颠倒二进制位
  • vulhub搭建漏洞环境docker-compose up -d命令执行报错以及解决方法汇总
  • C++ 简介
  • shardingjdbc分库分表原理
  • C++泛型编程:模版
  • 一道涉及 Go 中的并发安全和数据竞态(Race Condition)控制的难题
  • 如何降低H5商城系统的开发成本
  • 为什么越来越多的网工运维转行网络安全?_idc运维转网络安全工程师_系统运维转行网安
  • 【TabBar嵌套Navigation案例-产品推荐页面-UICollectionView-结合xib使用 Objective-C语言】
  • java.nio.ByteBuffer的 capacity, limit, position, mark
  • 握手传输 状态机序列检测(记忆科技笔试题)_2024年9月2日
  • 电商跨境电商商城系统/网上商城接口/电商数据接口详情
  • openFrameworks_如何使用ofxXmlSettings和ofxGui来创建识别界面
  • 180多个GIS地理空间定义术语中英文对照配图
  • Vue(14)——组合式API①
  • 【图像检索】基于颜色模型的图像内容检索,matlab实现
  • 看过来——量子计算中一个神奇符号的解释
  • 传输层 IV(TCP协议——流量控制、拥塞控制)【★★★★】
  • Java设计模式全面解析
  • spring全家桶使用教程
  • REST-系统架构师(六十九)
  • SAP B1 营销单据 - 复制从复制到总结
  • css设置overflow:hiden行内元素会发生偏移的现象
  • 使用多个 GitHub 账号的 SSH 配置与常见问题排查
  • sql语法学习
  • 滚雪球学SpringCloud[5.3讲]: 配置管理中的高可用与容错
  • 电商安全新挑战:筑起数字防御长城,守护业务与数据安全
  • Python 单元测试:深入理解与实战应用20240919
  • 二、MySQL环境搭建
  • mongoDB 读取数据python版本实现