在 axios 请求后附加到 headers object 的问题

Issue appending to headers object after axios request

所以我的初始请求 getBookingSessionId 获取一个 ID,该 ID 需要在我的 axios.create() 方法中传递到我的 headers object 中,以便它可以在我的下一个中使用要求。

import axios from 'axios';
import { strings } from '../strings';

class CorasApi {
  constructor() {
    const url = 'https://sandbox.coras.io';
    this.bookingSessionId = null;

这会创建一个 axios 实例并保存我的 headers

      this.request = axios.create({
      baseURL: url,
      headers: {
        'Coras-Distributor': strings.coras.distributorId,
        'Content-Type': strings.coras.contentType,
      }
    });
  }


 getBookingSessionId = () => {
 return new Promise((resolve, reject) => {
  this.request
    .post('/booking-session/', null, null, {})
    .then(res => {
      //   debugger;
      resolve(res);

我在这里尝试将我的请求结果附加到我的 headers object

      this.bookingSessionId = res.data['booking-session'];
      this.request.headers.append('Booking-Session', this.bookingSessionId);
    })
    .catch(err => {
      reject(err);
    });
});
};

这是下一个需要 'Booking-Session' header

的请求
 async getShows() {
  await this.getBookingSessionId();
  return new Promise((resolve, reject) => {
   this.request
    .get('/events/', null, {})
    .then(res => resolve(res))
    .catch(err => {
      reject(err);
    });
});
}

根据 docs,您可以在创建实例后更改默认值。

getBookingSessionId = () => {
   return new Promise((resolve, reject) => {
     this.request
       .post('/booking-session/', null, null, {})
       .then(res => {
         resolve(res);
         this.bookingSessionId = res.data['booking-session'];
         // this.request.headers.append('Booking-Session', this.bookingSessionId); 
         this.request.defaults.headers.common['Booking-Session'] = this.bookingSessionId; // replace the line above with this
       })
       .catch(err => {
         reject(err);
       });
   });
 };