Below is my protect route, which uses the jwt token to verify the user. I have tested the route using Postman and I receive the id, name which is correct. What I am trying to achieve is send a GET request using Fetch API to get this data and display it on my Profile component which I found on the react docs. I have also included how I have tried however all suggestions are welcome.
{
"id": 8,
"name": "Kie",
"iat": 1563135959,
"exp": 1563137399
}
/me route
router.get('/me', function(req, res) {
var token = req.headers['x-access-token'];
if (!token)
return res.status(401).send({ auth: false, message: 'No token provided.' });
jwt.verify(token, secret, function(err, decoded) {
if (err)
return res
.status(500)
.send({ auth: false, message: 'Failed to authenticate token.' });
res.status(200).send(decoded);
});
});
Profile Component
import React, { Component } from 'react';
import jwt_decode from 'jwt-decode';
class Profile extends Component {
constructor() {
super();
this.state = {
Items: [],
hasErrored: false,
isLoading: false
};
}
componentDidMount() {
fetch('http://localhost:5000/api/me')
.then(response => {
if (!response.ok) {
throw response;
} // Return the complete error response for debugging purposes
return response.json(); //we only get here if there is no error
})
.then(json => {
this.setState({ Items: json.Items });
});
// .catch(error => {
// () => this.setState({ hasErrored: true, error }); // Save both error flag and error detail so you can send it to tools like bugsnag
// / });
}
render() {
// if (this.state.hasErrored) {
// return <p>There was an error loading the items</p>;
// }
if (this.state.isLoading) {
return <p>Loading...</p>;
}
return (
<div>
<ul>
{this.state.Items.map(item => (
<li key={item.ID}></li>
))}
</ul>
</div>
);
}
}
export default Profile;