how to attach a header in axios.all()

Viewed 609

Is there any way to attach a header in axios.all method or do we have to attach the header to each request individually.

axios.all([
    axios.delete('http://localhost:5000/requests/'+{id}),
    axios.post('http://localhost:5000/records/'+{id, response}),
],{
    headers: {Authorization: localStorage.getItem('auth-token')}
}).then(res => console.log(res.data))
.catch(err => console.log(err));
2 Answers

Create an axios instance and use the same instance for all requests (recommended)

const axiosInstance = axios.create({
  headers: {'X-Custom-Header': 'foobar'}
});

Sample:

const axiosInstance = axios.create({
  headers: {
     Authorization: localStorage.getItem('auth-token')
  }
});

axios.all([
  axiosInstance.delete("http://localhost:5000/requests/" + {id}),
  axiosInstance.post("http://localhost:5000/records/" + {id, response})
  ]).then((res) => {
    console.log("Response: ", res);
  }).catch((error) => {
    console.log("Error: ", error); 
  })

You can set up the default headers for all the requests as given

axios.defaults.headers.common['Authorization'] = token;

After setting this, All subsequent network calls will carry the Authorization header by default. This workaround will help you to provide application global header like Authorization header. You can create separate Axios instance as

const axiosInstance axios.create({
  headers: {Authorization: token}
});

You can choose one of the workarounds.

Related