Axios请求后如何将Booking-Session ID追加到headers对象供后续请求使用?
解决Axios实例中动态添加请求头的问题
嘿,我明白你遇到的麻烦了——你想把获取到的Booking-Session ID添加到Axios实例的请求头里,供后续请求使用,但一直没成功对吧?让我帮你拆解问题,然后给出修复方案。
问题根源分析
你代码里的核心问题有两个:
- 错误操作Axios实例的headers:
this.request.headers并不是你需要修改的对象,Axios实例的默认请求头存储在defaults.headers.common(通用请求头,所有请求都会携带)里,而且它不是DOM的Headers对象,不能用append方法。 - 冗余的Promise嵌套:Axios的
post/get方法本身就返回Promise,不需要再用new Promise包裹,这会增加代码复杂度还容易引发逻辑问题。
修复后的完整代码
下面是修改后的CorasApi类,我会标注关键改动:
import axios from 'axios'; import { strings } from '../strings'; class CorasApi { constructor() { const url = 'https://sandbox.coras.io'; this.bookingSessionId = null; this.request = axios.create({ baseURL: url, headers: { 'Coras-Distributor': strings.coras.distributorId, 'Content-Type': strings.coras.contentType, } }); } // 重构getBookingSessionId:去掉冗余Promise,正确设置请求头 getBookingSessionId = async () => { try { // Axios post本身返回Promise,直接await即可 const res = await this.request.post('/booking-session/'); this.bookingSessionId = res.data['booking-session']; // 关键:修改Axios实例的通用默认请求头 this.request.defaults.headers.common['Booking-Session'] = this.bookingSessionId; return res; } catch (err) { throw err; } }; // 重构getShows:简化Promise逻辑 async getShows() { // 先确保获取到Session ID并设置好请求头 await this.getBookingSessionId(); try { const res = await this.request.get('/events/'); return res; } catch (err) { throw err; } } }
进阶优化:用请求拦截器自动管理请求头
如果后续有多个请求都需要携带Booking-Session ID,推荐用Axios的请求拦截器来自动处理,这样不用在每个请求前手动调用getBookingSessionId,代码更健壮:
import axios from 'axios'; import { strings } from '../strings'; class CorasApi { constructor() { const url = 'https://sandbox.coras.io'; this.bookingSessionId = null; this.request = axios.create({ baseURL: url, headers: { 'Coras-Distributor': strings.coras.distributorId, 'Content-Type': strings.coras.contentType, } }); // 添加请求拦截器:自动检查并添加Booking-Session头 this.request.interceptors.request.use(async (config) => { // 如果还没有Session ID,先获取 if (!this.bookingSessionId) { await this.getBookingSessionId(); } // 给当前请求注入请求头 config.headers['Booking-Session'] = this.bookingSessionId; return config; }, (error) => { return Promise.reject(error); }); } getBookingSessionId = async () => { try { const res = await this.request.post('/booking-session/'); this.bookingSessionId = res.data['booking-session']; return res; } catch (err) { throw err; } }; // 现在getShows可以简化成这样 async getShows() { try { // 拦截器会自动处理Session ID的获取和注入 const res = await this.request.get('/events/'); return res; } catch (err) { throw err; } } }
这个拦截器的好处是:所有通过this.request发起的请求都会自动检查Session ID的状态,如果不存在就先获取,然后注入请求头,完全不用你手动管理。
内容的提问来源于stack exchange,提问作者Harry Condron
相关产品推荐
相关产品推荐

