传递一个对象参数
诸如post()
和get()
等Axios方法使我们能够在请求中附加头信息,方法是将头信息对象作为GET
请求的第二个参数和POST请求的第三个参数
这段代码为所有请求设置了授权头信息
注意 axios.defaults.headers.common['Authorization']里面是有 ' ' 引号的
axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('access_token')`;
实际案例:在request.js里面封装的axios方法里的请求拦截器里
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import store from '@/store';
import { localStorage } from '@/utils/storage';
// 创建axios实例
const service = axios.create({
baseURL: import.meta.env.VITE_APP_BASE_API, //VITE_APP_BASE_API开发环境
timeout: 50000, // 请求超时时间:50s
headers: { 'Content-Type': 'application/json;charset=utf-8' },
});
// 请求拦截器
service.interceptors.request.use(
(config) => {
console.log(config)
if (!config.headers) {
throw new Error(`Expected 'config' and 'config.headers' not to be undefined`);
}
const { isLogin, tokenObj } = toRefs(store.user.useUserStore());
//拿到存在本地里的tokenObj,
if (isLogin.value) {
// 授权token认证 设置token
config.headers['token'] = tokenObj.value.token;
}
return config;
},
(error) => {
return Promise.reject(error);
},
);
//响应拦截器
// 导出实例
export default service;
单个请求
POST和GET请求分别用于创建或检索一个资源。下面是一些一次性或单个请求的例子。
首先,我们声明config
对象,其中包含headers
对象,它将在提出请求时作为一个参数提供。我们还声明了一个api endpoint
和一个data
对象。
const config = {
headers:{
header1: value1,
header2: value2
}
};
const url = "api endpoint";
const data ={
name: "Jake Taper",
email: "taperjake@gmail.com"
}
我们可以使用GET请求从API端点url
检索config
对象。
axios.get(url, config)
.then(res=> console.log(res))
.catch(err=> console.log(err))