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?

1

1 Answer 1

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'}] });
Sign up to request clarification or add additional context in comments.

2 Comments

@CatarinaBatista sorry this was a pseudocode, updated to a working example
I just change headers = [...headers, ...additionalHeaders] to headers = {...headers, ...additionalHeaders} and [{'Content-Type': 'application/json'}] to {'Content-Type': 'application/json'} Thank you so much :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.