The Express.js Route to Success | express.js router

You probably want your node.js server to respond to requests that are coming in, specially when you are building a website in this site https://www.webdesign499.com/5-types-of-content-every-business-website-should-have/. This can be complex and quite tedious to implement in vanilla node.js. Luckily express.js has done this for you.

Basic Routing

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.

To get access to the query parameters you can use the params object that is available though the _req _argument in the handling of the request. Since JavaScript isn’t strongly typed, you can just access the 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:

How to build node.js apps effortlessly with express.js

Node.js is a pretty powerful and versatile framework to build sites and tools. But using the defaults to handle HTTP requests and such can be a pain. Express.js can make your life a lot easier.

In the previous tutorial I showed you how to get started with node.js, this time I’m going to expand on that. We’re going to scaffold a new Express.js app.  Express.js is a web framework that makes it very easy to handle calls to the node.js server. It helps you with routing, error handling and it works very well other frameworks.

Installing the express generator

The easiest way to get going with any Express.js-based node.js app is by using the express-generator. I’ve you are planning to use it multiple times (and trust me, you will), run the following command and install the express-generator globally.

This might take a moment, but if it’s done installing you should be able to run the ‘express’ command with the ‘-h’ flag to display the help.

Options are limited, but that’s fine. You can select a one of a few common view engines and stylesheet engines. Personally I prefer pug and sass. I plan on doing an entire tutorial on pug soon.

Run the following command to bootstrap the new app.

Next, to install the necessary dependencies, run ‘npm install’.

…and wait…

When it’s eventually done, run ‘npm start’ to start your new application and go to the browser at http://localhost:3000 to view your node.js app running.

This was the easy part… now lets go into a bit more detail on what this has generated.

The App

Left you can see a partial screenshot of the app opened in Visual Studio Code. Let’s go over the folders and let me briefly explain what these contain. In a later tutorial we’ll dive deeper in much of the concepts.

At the top you find a ./bin folder. In there is a _‘www’. _This file actually contains the JavaScript needed too start your server. It handles the port at which the server is running. And it literally creates a server for your app.

Which brings to the next important file. Near the bottom of the list you can find ‘app.js‘. In here the express.js app is instantiated and the root level routing is configured. This means that there is some the app is told at what url specific could should be called to handle the requests. It also configures the apps view engine (pug) and the css engine (sass).

Inside the ./views folder there are 3 .pug files. These files are used by the _pug_ view engine and contain the markup of the app.

Then there are the 2 .js files in the ./routes folders. These two handle the requests on the root level routing configured in app.js. What happens is that a request comes at the server, say an HTTP GET request at url http://localhost:3000/users. The url /users is configured in app.js and points to the users.js file in ./routes. Inside users.js the request is taken from there, so the HTTP GET is handled from ‘/’ and a string is placed in the response.

Last, there’s the public folder. This folders is configured in app.js as the location from which static files are served. In fact, this folder is mapped to the root url. So http://localhost:3000/stylesheets/style.css returns the css file, note that there’s no ‘public’ part in that url.

When using Gulp or Grunt to compile your JavaScript and Sass, the resulting files are placed in the public folder.

 

 

Getting started with Node.js on ChakraCore

Intro

Last year I started to use Node.js more and more. Personally I really like it. Using node.js on ChakraCore has some advantages over using V8. I’ve decided to get to know node.js a bit better and start a series of posts about it, beginning from the top.

What is node.js?

Node.js is described as interface to V8, Google’s JavaScript engine that also used in Chrome. Node.js enable you to write server-side code using JavaScript. It is uses an event-driven, non-blocking I/O mode.  This  very lightweight and efficient, but, as a trade off, you have have to implement every HTTP status code yourself. Fortunately there are a lot of libraries that can help you with that. Packages are distributed by the node.js’ packaging system, npm, which happens to be the largest ecosystem of open source libraries in the world.

Why use ChakraCore?

I was mentioning ChakraCore a few times already. What the heck is that? ChakraCore is the core part of Chakra, Microsoft’s JavaScript engine, the engine that powers Microsoft Edge. ChakraCore is open source, runs cross platform and is also very fast and efficient. So technically it should be possible to replace V8 in node.js with ChakraCore. And it is. Since everything is open source nowadays, Microsoft forked node.js and created a shim for the V8 API, ChakraShim, to make node.js use ChakraCore.

The fact that node.js can run on ChakraCore isn’t the best reason by itself. But there is another bigger advantage in using ChakraCore:

Time Travel Debugging

Every developer knows about placing breakpoints, hitting them and stepping through the code from there. But what if you are just passed the point that has the issue you want to investigate? You normally would place a breakpoint at another place and rerun your application, bringing it to the same state and trying to hit that breakpoint. Wouldn’t it be great if you didn’t have to go though all of that and could just step backwards? That’s exactly what Time Travel Debugging can do.

Set up

Let’s get node.js up and running. The easiest way to get going us by using the node-ChakraCore version switcher, nvs. You can download that here.

After installing nvs  go to command prompt or PowerShell and run ‘nvs’. Now you can select a ‘remote’. This is will be the node.js type to use.

After selecting a node.js, you can specify the exact version to use:

Wait for it to download and install…

After it is installed you should be able to request the version with “node –version”.

Getting up and running

Now we have node.js running we could begin developing an application. I’m going to start with a very simple application using express.js.

In a later tutorial I’m going to show you how you can scaffold using express.js, but for now let’s get a simple app running.  I always start with creating a new folder, let’s call it ‘NodeDemo’ and ‘cd’ into that.

Node.js comes with a package manager, npm. That’s one of the most used standards in JavaScript development nowadays. It can do a lot more than only managing packages, but we’ll save that for a later tutorial.

The use of npm has to be initialized inside the folder we just created run ‘npm init’. You can fill out the questions asked, or just enter through for now, until you’re back at the commandline. This will create a package.json file in which the packages used by the project are stored.

Next, let’s add the package for express.js by running the folling command: ‘npm install express –save’. The –save options makes sure the use of the package is registered into the package.json file.

Last thing to do is use the express.js package in an app. It’s time to start Visual Studio Code. You can do that by running ‘code .’ in the commandline (note the period at the end). Add a file, ‘app.js’ and add the following code.

<!– pre>var express = require(‘express’); var app = express();

app.get(‘/’, function (req, res) { res.send(‘Hello World!’); });

app.listen(3000, function () { console.log(‘Example app listening on port 3000!’); }); This small piece of code does a few things. The first part loads express.js and initializes it.

After that it registers an HTTP GET on the root url ‘/’. When an GET is performed the function is called and a response is send to the client.

The last part starts the app listening on port 3000 and logs a message to the console when it’s started.

If you followed along, you should be able to run the app now. Go back to the commandline and type:’node app.js’.

Now you should be able to navigate to http://localhost:3000 and see the app running…

And that’s it.

Styling console.log output

I recently learned about a very cool console.log feature. You can use CSS formatting to style the output of console.log. And it’s very easy. All you have to do is use the ‘ %c ‘ formatting tag in your message. Here’s a simple example:

console.log('%cThis is a %cfun%c console message',
            'font: 24px serif; font-weight:100; color: #228;',
            'font: 30px sans-serif; font-weight:800; color: #F44;',
            'font: 24px serif; font-weight:100; color: #228;'
        );

When you look in the console of the browser, you should see something like this:

fun-console-message

Unfortunately this features is not supported in all browsers, which may result in a whole bunch of CSS being written to the console. You should check the browser in your code before using this feature. As far as I know only Chrome and Firefox support this feature.

Poor Mans jQuery

A lot of people use jQuery in their HTML/JavaScript applications. There’s nothing wrong with that. But I’ve seen a lot of people use jQuery only to make it easy to find elements and they are not using any of the other jQuery functions. It’s pretty clear that writing a single ‘ $ ‘ instead of the way longer usages of various function on the ‘document‘ object, like getElementById. One of the functions on the ‘document’ object is the querySelectorAll function. This function brings a similar experience to vanilla JavaScript by taking selectors as a parameter.  So if we take a look at the example below. This show a fairly complicated selector you might find in an application.

I personally don’t like writing ‘document.querySelectorAll every time I need to find some things in the DOM, and many people with me. That’s why a lot of developers include jQuery in their project. To be able to use a similar syntax as jQuery is using I often add the following line somewhere at the start of my JavaScript code:

window.$ = function (selector) { return document.querySelectorAll(selector); };

Here’s the earlier example, but with the poor-mans-jQuery added.

It’s not perfect and sometimes I add a context or something to that function if it is needed for that project, but it works fine in most cases.

As a last note, always look at the performance. If you are using selectors a lot, like in a big for-iteration, you might want to use the document.getElementsByClass function or something similar. These have less overhead and are somewhat faster.