Search code examples
reactjsinterceptor

OpenAPIClientAxios Interceptor to Set a header in React


I am using OpenAPIClientAxios to call apis. What I need is when there is a request going out, I would like to add a header to the request.

I tried something like

import axios from "axios";
export function jwtInterceptor() {
axios.interceptors.request.use(request => {
    if (request.headers) {
        request.headers['test'] = 'test1234';
    }
    return request;
});}

However, it's never been called. I suspect it has something to do with OpenAPIClientAxios but not sure how to fix it. Any recommendation please?


Solution

  • I created a function like:

    const updateHeaderInterceptor = (axiosInstance: AxiosInstance) => {
    axiosInstance.interceptors.request.use((config) => {
        if (config !== undefined && config.headers !== undefined) {
            alert(1)
            config.headers["test"] = "test1234";
        }
        return config;
    }, (error) => {
        alert(error)
    });}
    
    export default updateHeaderInterceptor;
    

    And then call this wherever an instance of the client (OpenAPIClientAxios) is created so we can pass the client to this function.