import React, { Component } from 'react'
import axios from 'axios';
class QuestionAPI extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
MYTOKEN: "cqondiodwoidndndjjajajejh.ndoqndnodnqodoqdiapoe89wnwjwmalmqql2mkKKMkmwk"
};
}
componentDidMount = (MYTOKEN) => {
axios.get(`http://192.168.0.10:9000/getquestions`,{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
"token": 'Bearer' + MYTOKEN
},
})
.then(res => {
console.log("res" + res)
})
.catch(e => console.log(e))
}
render() {
return (
<div>
</div>
);
};
}
export default QuestionAPI;
There are a few issues with your code.
The componentDidMount
method doesn't receive any arguments. So, you have to get the token from localStorage
(assuming you're storing the token in it). And you should remove the hardcoded token from the component state.
The token should be sent in the Authorization
header (your code sends it in token
and that's why the API sends a 401 Unauthorized
response). And there should be a space next to Bearer
.
Authorization: `Bearer ${token}`
REACT_APP_
to .env
or you can use dotenv-webpack if you have a custom Webpack setup.componentDidMount = () => {
const token = localStorage.getItem('token') // Replace token with the right key
if (!token) {
// handle no token case
return
}
axios.get(`${process.env.API_BASE_URL}/getquestions`, {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${token}`,
},
})
}