0

I have my http class which uses axios, and it has a method for setting authorization token into headers:

export class Http { constructor(private readonly _axios: AxiosInstance) { this.useInterceptors(); } setAuthorizationHeader(token: string): void { this._axios.defaults.headers.common.Authorization = `Bearer ${token}`; } unsetAuthorizationHeader(): void { delete this._axios.defaults.headers.common.Authorization; } private useInterceptors(): void { this._axios.interceptors.response.use( undefined, (error: AxiosError): Promise<AxiosError> => { if (error.response?.status === 401) { store.dispatch(actions.auth.signOut()); } return Promise.reject(error.response?.data); }, ); } get get() { return this._axios.get; } get post() { return this._axios.post; } get put() { return this._axios.put; } get patch() { return this._axios.patch; } get delete() { return this._axios.delete; } get request() { return this._axios.request; } get axios(): AxiosInstance { return this._axios; } } export const http = new Http( axios.create({ baseURL: API_URL, timeout: 60000, }), ); 

also I have my middleware for authorization:

export const authMiddleware = () => (next: Dispatch) => (action: AnyAction): AnyAction => { if (action.type === 'client/code/fulfilled') { action.payload?.token && http.setAuthorizationHeader(action.payload.token); } if (action.type === REHYDRATE) { action.payload?.auth?.token && http.setAuthorizationHeader(action.payload.auth.token); } if (action.type === actions.auth.signOut.type) { http.unsetAuthorizationHeader(); } return next(action); }; 

And I have a problem, when I console.log axios common headers I don't see there Authorization. What could be a cause of this?

6
  • add log statements when you set/unset the Authorization header in the Http class. This will give you a better idea of whats happening. Commented Jun 26, 2022 at 16:40
  • @Francisco Garcia I did it. This methods calls, and I had a also get token there, but when I trying console.log('headers', axios.defaults.headers.common);, a still don't see my Authorization header. Also I added log into my unset method and it dons calls. Commented Jun 26, 2022 at 16:48
  • 1
    Do you log before your actions fire? Also, check that you are logging the headers in the appropriate axios instance (use the instance passed to your Http class) Commented Jun 26, 2022 at 16:53
  • @Francisco Garcia it works, i used log inside my http class, and there is my custom header Commented Jun 26, 2022 at 17:19
  • Does this answer your question? Axios not sending headers, post request failing, getting 401 Commented Jun 26, 2022 at 18:05

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.