Reputation: 177
This the endpoint in my api that I am trying to access
router.get('/:id', [jsonParser, jwtAuth], (req, res) => {
return Teams.find().sort({creator: req.params.id})
.then(teams => res.status(200).json(teams))
.catch(err => res.status(500).json({message: 'Internal server error'}));
});
The fetch will probably look something like this?
function viewProfile() {
const base = '/api/teams/';
const id = idFromJwt;
const url = base + id;
return fetch(url)
.then(res => res.json())
.then(response => {
//takes response and modifies DOM
populateProfile(response);
})
.catch(err => console.log(err));
}
Upvotes: 0
Views: 2443
Reputation: 4059
First of all, assuming you're using ExpressJS
I do suggest leveraging express-jwt
middleware to handle requests authentication and issuing new Tokens.
What you need to bear in mind is that, you need to include the userId
when you authenticate the user in the JWT payload in order to be able to retrieve it from the payload afterwards.
When user is authenticated, you have to store the token in the state of your application or in the localStorage
or sessionStorage
.
In case you want to decode the token on the front-end side and then send it to the API, you can use a simple module called jwt-decode
to achieve that:
const jwtDecode = require("jwt-decode");
const token = window.localStorage.getItem("token"); // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWQiOiIxMjM0NTY3ODkiLCJpYXQiOjE1MTYyMzkwMjJ9.gHqSxzWpdOUL1nRAqUJg2CtjsEZZi8FLikD41i639zY
const tokenPayload = jwtDecode(token).id; // "123456789"
Please bear in mind that in case you decided to use express-jwt
you need to also send the token in the headers of the request as authorization
to authenticate.
Hope it helps. :)
Upvotes: 1