安装axios
yarn add axios
npm install axios
封装请求配置拦截器
在src/api/axios.js
中封装我们的请求。
import axios from "axios";
import {useCommonStore} from "../store/module/common.js";
import {storeToRefs} from "pinia";
// 设置接口超时时间
axios.defaults.timeout = 60000;
// 请求地址
axios.defaults.baseURL = '';
// http request 拦截器
axios.interceptors.request.use(
config =>{
// 获取token
const commonStore = useCommonStore()
const { token } = storeToRefs( commonStore )
console.log('token',token.value)
// 配置请求头
config.headers = {
// 'Content-Type':'application/x-www-form-urlencoded', // 传参方式表单
'Content-Type': 'application/json;charset=UTF-8', // 传参方式json
'Authorization': `Bearer ${token.value}`, // 设置Authorization
// 'token': token.value // 或者设置token
};
return config;
},
error => {
return Promise.reject(error);
}
)
// http response 拦截器
axios.interceptors.response.use(
response => {
return response;
},
error => {
const { response } = error;
if (response) {
// 判断错误状态码
if (response.status === 400) {
// 请求400
} else if (response.status === 401) {
// 未授权,请重新登录
} else if (response.status === 403) {
// 拒绝访问(403)
}
return Promise.reject(response.data);
} else {
console.log('网络连接异常,请稍后再试!')
}
}
)
// 封装 get post 请求
export function request (url,params = {},type = 'POST') {
return new Promise((resolve,reject) => {
let promise
if (type.toUpperCase() === 'GET') {
promise = axios({url,params})
} else if (type.toUpperCase() === 'POST') {
promise = axios({
method: 'POST',
url,
data: params
})
}
promise.then( res => {
resolve(res)
}).catch (err => {
reject(err)
})
})
}
api统一管理
在src/api/api.js
文件中统一管理我们的接口api
// 引入 request
import { request } from "./axios.js"
// 模块化接口
export class UserApi {
static async login(params) {
return request('/login',params,'post')
}
static async register(params) {
return request('/register',params,'post')
}
static async getUserInfo(params) {
return request('/userInfo',params,'get')
}
}
export class BookApi {
static async getBookList(params) {
return request('/bookList',params,'get')
}
}
应用
<script setup>
import {UserApi} from "../api/api.js";
const login = async () => {
const params = {
username: 'admin',
password: '123456',
}
const res = await UserApi.login(params)
}
</script>
跨域问题
在vite.config.js
配置。
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
server: {
host: '127.0.0.1',
port: 3000,
proxy: {
'/api': {
target: '', // 实际请求地址
changeOrigin: true,
rewrite: (path) => path.replace(/^/api/, '')
}
}
},
}
观看更多相关文章请关注公众号:
原文始发于微信公众号(大前端编程教学):vue3+axios 封装拦截器
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/224253.html