Reputation: 2817
I'm learning how to build server with authentication. I'm following this tutorial, the final code can be found here. Which uses Express
and JWT
to build a simple login server. The following code:
app.use((req, res, next)=>{
// check header or url parameters or post parameters for token
console.log(req.body);
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if(token){
console.log("token");
jwt.verify(token,"samplesecret",(err,decod)=>{
if(err){
res.status(403).json({
message:"Wrong Token"
});
}
else{
console.log("success");
req.decoded=decod;
next();
}
});
}
else{
res.status(403).json({
message:"No Token"
});
}
});
is adding a middleware, but I'm not sure what the purpose of this is and how it works. Is this being called on every route? What is req.body
in this case? And what does res.status().json()
do?
I also don't understand what the script auth
and getlist
under the HTML file does (too long to include). When are these scripts being called? Are they storing a cookie
on the user's computer? What's being authenticated?
This is a lot of questions and I apologize. I'm quite new to web-dev, just want to figure out the fundaments. Thanks a bunch.
Upvotes: 3
Views: 276
Reputation: 2738
This is being called on every route to check for an existence of a token, decode, and check it.
If present, and decoded, (where it says console.log('success');
) it is attaching the data decoded from the jwt to the request req
so that in any of the controllers where you handle the request you can have the data (stored on req.decoded
)
As far as res.status().json()
(res
of course meaning response)...
2 functions are being chained that are functions of res
.
status(int)
json(obj)
req.status
sets the response status code (eg 200 OK, 404 Not found, 503 Server error).
req.json
send the response with the body being the json you pass in.
So the following would send the message {error:'We failed'} back to the client with a http status code of 503:
req.status(503).json({ error: 'We failed' });
You can read more about response methods/properties like this (and others like send
, redirect
, ect) on the Express documentation here.
Upvotes: 1