Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach custom headers before every fetch request in react native

How can i configure my react application to attach some custom request before every http request? We had $httpProvider in angularjs for the same purpose. What is the way of doing it in react?

like image 488
Rakesh Yadav Avatar asked May 24 '26 16:05

Rakesh Yadav


1 Answers

Just wrap the call in a function and add the headers?

global.FetchWithHeaders = async function(verb, url, data){
    const request = {
            method: verb,
            headers: { 'X-Auth-Token': '[Example Header Token]' }
        };

    if (data)    {
        request.body = JSON.stringify(data);
    }

    const responseObj = await fetch(url, request)
        .then(function(response){
            //Do something with response
            console.log(response);
        });

    return responseObj;
};

Could sit in a base Component or in global like above. Depends how you want to use it?

like image 71
Jamadan Avatar answered May 27 '26 08:05

Jamadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!