-
Notifications
You must be signed in to change notification settings - Fork 6
Creating Express Routes
We use Express for our API routing. Express makes it really easy to declare and handle new routes.
Let's use the authentication routes as an example.
To create a route, we need a reference to the router, which we can get by simply importing it
var router = require('express').Router()
Now, we can declare our route
router.post('/login', function (req, res) {
// Route Handler
});
Without actually responding to the request, the client will be left hanging. Luckily, it's easy to respond with Express.
res.send({
status: true
});
This is a decent response for a successful login request, but how do we handle errors?
res.status(401).send({
status: false,
message: Responses.USER_EXISTS
});
Here we send back a 401 status code as well as an error message. Our practice for sending messages back to the client is to have a dedicated place in the /responses/
folder. This is a nice abstraction for common messages.
It is important to have a good response back to the user.
Finally, we must export our router like we do everything else
module.exports = router;
In api.js
, we declare our handlers for groups of routes. Following our authentication example, we are putting all those routes into the authHandler.
var authHandler = require('./api/auth.js'); // auth.js is where /login is declared
We can now tell our router to namespace these routes in a way.
router.user('/auth', authHandler);
Now, all requests with /auth
as a prefix will be directed to the authHandler.