Skip to content
This repository has been archived by the owner on Apr 22, 2024. It is now read-only.

Creating Express Routes

Connor Krupp edited this page May 17, 2017 · 2 revisions

Routing

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.

Declaring a Route

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
});

Sending Responses

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.

Exporting the Router

Finally, we must export our router like we do everything else

module.exports = router;

Exposing the Route

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.

Clone this wiki locally