当前位置: 首页> 科技> 名企 > 郑州新闻头条_网站策划与运营考试题_电商网站排名_网站批量查询工具

郑州新闻头条_网站策划与运营考试题_电商网站排名_网站批量查询工具

时间:2025/7/13 22:27:27来源:https://blog.csdn.net/weixin_43671437/article/details/142451650 浏览次数:0次
郑州新闻头条_网站策划与运营考试题_电商网站排名_网站批量查询工具

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 => {if (error.code === 'ECONNABORTED'){console.log('服务器连接中断')router.replace('/login')return Promise.reject(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)
})
关键字:郑州新闻头条_网站策划与运营考试题_电商网站排名_网站批量查询工具

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: