0

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?

Catarina
  • 359
  • 3
  • 16

1 Answers1

2

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'}] });
Eugene
  • 10,006
  • 4
  • 37
  • 55
  • @CatarinaBatista sorry this was a pseudocode, updated to a working example – Eugene Oct 02 '19 at 14:11
  • I just change `headers = [...headers, ...additionalHeaders]` to `headers = {...headers, ...additionalHeaders}` and `[{'Content-Type': 'application/json'}]` to `{'Content-Type': 'application/json'}` Thank you so much :) – Catarina Oct 02 '19 at 14:32