Ad

How To Add A Header Into Post API Using Axios In React?

- 1 answer

I'm trying to make a post API with axios. I have a component with axios syntax:

export function postAPI(callback, url, body) {    
    axios.post(url, body, { headers: { 'Key': '*******'}})
        .then(res => callback({ data: res.data, isLoading : false }))
        .catch(err => callback({ error: err, isLoading : false }));
}

and I'm doing a request like this:

 postAPI(result => {
     const { data, error } = result;

     if (error) {
           alert('error')    
     }
     if (data) {
           alert('success')
      }
 }, URL, body });

Objective: I have other post request that must have one more header, but I don't know how to do it in that case...

Someone can help?

Ad

Answer

Maybe something like this

export function postAPI(callback, url, body, additionalHeaders) {    
    let headers = [{ 'Key': '*******'}];
    if (additionalHeaders) {
      headers = [...headers, ...additionalHeaders];
    }
    axios.post(url, body, { headers })
        .then(res => callback({ data: res.data, isLoading : false }))
        .catch(err => callback({ error: err, isLoading : false }));
}

 postAPI(result => {
     const { data, error } = result;

     if (error) {
           alert('error')    
     }
     if (data) {
           alert('success')
      }
 }, URL, body, [{'Content-Type': 'application/json'}] });
Ad
source: stackoverflow.com
Ad