...

/

Creating REST API for the Course Management Application

Creating REST API for the Course Management Application

Learn how to create a REST API for the course management application.

To create the REST API for the course management app, we need to start by creating the verification token, which will help us authorize a user every time they request the client-side. The token will get sent to the server as an authorization header, and the server will then process the token and verify if it’s a valid one. If the token sent to the server is verified as correct, the API will grant the request. If not, an error will get returned.

Setting up the token verification

To set up the token verification middleware, we need to create a new file called verifyToken.js in the middleware folder of our node.js application. We then proceed to type the code below inside our file:

Press + to interact
const jwt = require('jsonwebtoken')
module.exports = (req, res, next) => {
const authHeader = req.headers.authorization;
if (authHeader) {
const token = authHeader.split(' ')[1];
jwt.verify(token, process.env.JWT_SECRET_KEY, (err, user) => {
if (err) {
return res.sendStatus(403);
}
req.user = user;
next();
});
} else {
res.sendStatus(401);
}
};

In summary, what we did above was:

  • In line 1, we import the jsonwebtoken npm package into our verifyToken.js file.
  • Next in line 3, we used the module.exports functionality that helps to export any function within it.
  • The module.exports was assigned a function with three arguments called req, res, and next.
  • In line 4, we create a variable called authHeader. This variable helps extract the bearer token passed when the request gets made using the REST API.
  • Next, in line 6, we create an if statement with the condition that if the authHeader which carries our token exists, then the logic between line 7 and line 13 should get executed. In a situation where
...