axios拦截器:仅将自定义标头添加到OPTIONS请求中

时间:2019-04-30 16:17:43

标签: javascript axios

所以我已经为axios设置了一个拦截器,并且正在向请求添加自定义标头。但是,当我签入服务器代码时。标头仅在OPTIONS请求中接收。

class ChainInterceptors {
  constructor(config) {
    this.cleanConfig = { ...config };
  }
  build() {
    return this.cleanConfig;
  }
}

export class ReqInterceptor extends ChainInterceptors {
  constructor(config) {
    super(config);
  }
  setLog() {
    this.cleanConfig.headers['Respond-By'] = // some value;
    return this;
  }
}

我正在通过以下方式实现它:

export const request = {
  init() {
    const token = getItem('token');
    const request = axios.create({
      httpsAgent: new https.Agent({ keepAlive: true }),
      baseURL: LOCAL_URL,
      headers: {
        authorization: `bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });
    this.attachInterceptor(request);
    return request;
  },

  attachInterceptor(request) {
    request.interceptors.request.use(config => {
      return new ReqInterceptor(config).setLog().build();
    });
    request.interceptors.response.use(
      response => {
        // response interceptors
      },
      error => {
        // Do something with response error
        return Promise.reject(error);
      }
    );
  },

  get() {
    return this.init().get.apply(null, arguments);
  },

  // and other methods...
};

如上所述,Respond-By标头仅出现在我的OPTIONS请求中。非常感谢您的指导。

1 个答案:

答案 0 :(得分:0)

我在拦截器中使用以下设置来传递令牌和当前语言。当前语言是自定义标头,我需要检测用户从客户端选择的当前语言。

config.headers [“ lang”] = ${lang}下; 是自定义标题。

从服务器端,我通过 _httpContextAccessor.HttpContext.Request.Headers [“ lang”]

来获取
export function setupAxios(axios, store) {
  axios.interceptors.request.use(
    config => {
      const {
        auth: { authToken },
        i18n: { lang }
      } = store.getState();

      // console.log("language => ", lang);
      // console.log("setupAxios => ", store.getState());

      if (authToken) {
        config.headers.Authorization = `Bearer ${authToken}`;
        config.headers["lang"] = `${lang}`;
      }
      store.dispatch(httpRequest.actions.startRequest(true));
      return config;
    },
    err => {
      store.dispatch(httpRequest.actions.endRequest(false));
      return Promise.reject(err);
    }
  );
  axios.interceptors.response.use(
    response => {
      store.dispatch(httpRequest.actions.endRequest(false));
      return response;
    },
    err => {
      store.dispatch(httpRequest.actions.endRequest(false));
      return Promise.reject(err);
    }

  );
}