TransWikia.com

how to attach a header in axios.all()

Stack Overflow Asked by Haider Abidi on December 28, 2020

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); 
  })

Answered by Kunal Kukreja on December 28, 2020

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.

Answered by Kiran Maniya on December 28, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP