How to pass Header JWT Token with Axios & React?
First of all when you login and send username and password to backend then in response you get token_id. now try to token store in session_storage and redirect to your desire page. now you take token_id in your desire page and store one variable as like..
let user = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id;
now you have token and pass in the header and get data in response
const api = `your api here`
axios.get(api, { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
this.setState({
items: res.data, /*set response data in items array*/
isLoaded : true,
redirectToReferrer: false
})
note : you should set blank items array in initial setState as like
this.state={
items:[],
isLoaded: false,
redirectToReferrer:false,
token:''
}
Include your token as authorization key as below.
axios.post(url,data, {
headers: {
'authorization': your_token,
'Accept' : 'application/json',
'Content-Type': 'application/json'
}
})
.then(response => {
// return response;
})
.catch((error) => {
//return error;
});