You probably want your node.js server to respond to requests that are coming in, specially when you are building a website. This can be complex and quite tedious to implement in vanilla node.js. Luckily express.js has done this for you.
Your node.js server needs to respond to event the most basic HTTP requests. If it doesn’t your website would be very boring. Express.js has functions for the 23( I thought there were like 8… :P ) most common HTTP methods. They all work in the same way. For example, to respond to an HTTP GET method on the root url you can do this:
Let’s dissect this piece. The app object is defined earlier and holds the current instance of the Express app. This object is instantiated at the beginning of your app.js file if you followed the description in my previous tutorial…
On the app object the get function is called. The first parameter of this function hold the URL on which the GET method should be handled. The second parameter is a function that is called when a request to the URL from the first parameter is coming in. This function has to have 2 parameters itself, an object containing all information of the request and an object you can use to create a response. In this case its send function is called with a string. This string will be send back to the client.
In a real-world application you probably end up with a lot of routes and handlers. You don’t want all of these handled inside you app.js. Express.js has you covered. This should be already inside the default app.js:
and if we look at that file at ./routes/index:
In the first part you can see that the index file is loaded with require. A few lines below that it is used. Instead of the get function the use function is used this time. Again, its first parameter is the route to cover, the second a Router object from Express.js. And that is it as far as the app.js goes. You’ll probably end up with a whole list of these use functions. The use function can be used for a lot more than only routing. If you want to use logging or authentication, this function can be used to specify middleware for that as well. Often the path parameter is omitted than.
The second part is located inside the ./routes folder by default. In this case I’m showing the default index.js file that’s in there. Right at the start of the file it loads ‘express’ and initialized the router.
After that the get function is called, again with a path. That path however starts at the location that is used in the app.js file. So for example when you do something like “app.use(‘/users/’,users);” in your app.js file, the path you use in the users.js file may look like “router.put(‘/description’, someFunction)”. In that case the URL for which the HTTP PUT verb handles “http://yourdomain.com/users/description”.
Handling query parameters
With handling calls to certain URLs, you also want to be able to handle query parameters or the message body send to that URL. Both are handled differently, so first let’s look at the query parameters.
Take the following URL: “http://yourdomain.com/users/p?name=sorskoot”. In the handling of the HTTP GET, you want to get access to the name parameter.
It’s nice to be able to use ‘ ? ‘ and stuff in the URL, but I personally would rather have the URL written like: “http://yourdomain.com/users/p/sorskoot”. In situations like that, express.js provides us with the solution. You can add a ‘ : ‘ to the path argument followed by the name of the parameter and the rest is handled automatically. The code would look like this in that case:
Now what if we want to use an HTTP POST? We don’t have a query string to pick parameters from. In that case we don’t use the params property, but the body property of the req argument. In the case below I want to POST something to “http://yourdomain.com/users/p”. Inside my users.js file I can handle this like:
More advanced routing
Sometimes you need to do more than one thing on a certain request or URL. Express.js provides a mechanism to have the routing being continuously checked. By calling the next() function that is passed to the route handler you do exactly that. You can have multiple callback handlers on the exact same route.
There are two more functions on the route that can be very useful when chaining handlers, ‘router.all()’ and ‘router.param()’. The ‘router.all()’ is similar to the ‘router.use()’ function, except that it handles all HTTP verbs. The ‘router.param()’ function adds a callback that triggers on the parameters. This function takes the name of the url parameter as an argument and is called when a url is routed that contains that parameter.
This means that you can have a routers that handle every path, that handle the parameters and that handle the HTTP verbs:
Keep in mind that the order of registering the handlers is significant. The param function is always called before the use of that parameter. But placing the all function after the get function, this having the wildcard path ‘ * ‘ later than the much tighter ‘/p/:name’ will cause the all function not being called.
Working with the response
When you are done handling the route you’ll probably want to send some response back to the client. There are a lot of specialized function you can use. I’m going to give you some information on the most common.
‘res.send()’ sends a response back to the client. This can be pretty much everything, a string, a JSON object or a Buffer. The content-length header is set automatically.
‘res.json()’ can be used to send a piece of JSON back to the client. Even though you can send JSON back using the send function, the json function provide a little bit more customization on the data. For example, you can specify the number of spaces used or specify a replacer function to further customize the parsing.
The last one I like to mention is ‘res.render()‘. This function uses to specified view engine to render a template to HTML.
Here are a few examples: