1.安装axios
npm i axios
在package.json中检查axios是否安装成功
"dependencies": {"axios": "^1.7.2","vue": "^3.4.29","vue-router": "^4.4.0"},
2.新建文件
新建文件utils/request.ts
import axios from "axios";
const service=axios.create({baseURL:'http://localhost:3000',timeout:5000
})service.interceptors.request.use(config=>{const token=localStorage.getItem('token')if(token){config.headers['Authorization']=`Bearer ${token}`}return config;},error=>{return Promise.reject(error);}
)
service.interceptors.response.use(response => {// 对响应数据做点什么return response.data;},error => {// 对响应错误做点什么console.error('Response error:', error);if (error.response) {// 这里可以处理HTTP状态码异常的情况switch (error.response.status) {case 401:// 未授权,跳转到登录页break;case 403:// 禁止访问break;case 404:// 资源未找到break;default:console.error('Unhandled error:', error.response.status);}}return Promise.reject(error);});export default service;
新建文件api/user.ts
import request from "../utils/request";
const api_name='';
export default {getData(url:any,params:any){return request({url:api_name+url,method:'get',params})},postData(url:any,params:any){return request({url:api_name+url,method:'post',data:params})}
}
3.在指定文件引用并使用
import getApi from '../api/user'
GET:
getApi.getData('http://jsonplaceholder.typicode.com/posts').then(res=>{console.log(res)})
POST:
getApi.postData('http://jsonplaceholder.typicode.com/posts',{"userId":1,"title":"sdf","body":"sdf"}).then(res=>{console.log(res)})