Programming Tutorials

  • View all tutorials
  • Creating routes in Express
    In the previous tutorial we covered how to get a simple Node.js application up and running with two basic routes. In this tutorial we'll cover how to create more complex routes that can respond differently to client requests.

    What is routing?

    As you saw in the previous tutorial, when a user visited either: http://localhost:3001/ http://localhost:3001/user?name=Robert then the application served two different pages for those url's. Routing is defining application end points that can respond to client requests. They can all be defined in a single JavaScript file that is run through Node.js, as we are doing in our app.js file.

    Static files

    You can allow users to access static files, e.g. text files, by setting a directory to serve only static files. In the root of the project directory create a directory called static, and then within it create a file called data.txt and add the following text to it: Hello world I am text within a file! Now you'll see if you try and access it via the following url: http://localhost:3001/data.txt You'll get the following error, Cannot GET /data.txt, because we haven't created a route for the file. In the app.js file, add the following line of code: app.use(express.static('static')); Now if you try and access the same URL, you'll see the contents of the text file are displayed (you may need to restart the node.js server by pressing ctrl+c in your terminal, and then running it again with the command node app.js).

    Parameters

    We already created a route that takes in a parameter, namely, the /user route. We can get the parameters in the url via the req.query object. If we visit the following url: http://localhost:3001/user?name=Robert Then we can access the value of the name parameter with the following line of code: req.query.name There is another way to access URL parameters with Express though, and that's via the req.params object. We'll add the following route to our app.js file: app.get('/user/:name', function (req, res) { var check = Users[req.params.name]; if (check) { res.render('user', { name: req.params.name, info: check }); } else { res.send('User does not exist...'); } }); You can see that the route is basically the same code as the previous /user route, but this one uses the req.params object, which allows you to enter URL's like below (you may need to restart your node.js server to see the results properly in your browser): http://localhost:3001/user/Robert http://localhost:3001/user/David What this method of routing allows us to do is, instead of directing users to a URL like: http://localhost:3001/user?name=Robert&topic=books&show=10 which in theory would show Robert's profile, and then display his favorite top 10 books, we can direct users to the following URL's which are more readable and cleaner: http://localhost:3001/user/Robert/books/10 http://localhost:3001/user/Robert/movies/5 The above URL's won't actually work if you enter them in though because we haven't setup routes for them, but below is an example of how you would go about doing that: app.get('/user/:name/:topic/:show', function (req, res) { var check = Users[req.params.name]; if (check) { var list; var books = ['book1', 'book2', 'book3', 'book4', 'bookA', 'bookB', 'bookC']; var movies = ['movie1', 'movie2', 'movie3', 'movie4', 'movie5', 'movie6']; if (req.params.topic === 'books') { list = books.slice(0); } if (req.params.topic === 'movies') { list = movies.slice(0); } res.render('user', { name: req.params.name, info: check, list: list.slice(0, parseInt(req.params.show)) }); } else { res.send('User does not exist...'); } }); And then in our user.ejs file we can display the list of favorite books/movies with the following code: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>User page</title> </head> <body> <h1>Profile: <%= name %> </h1> <ul> <li> <b>Age:</b> <%= info.age %> years old </li> <li> <b>Occupation:</b> <%= info.occupation %> </li> <li> <b>Hobby is:</b> <%= info.hobby %> </li> </ul> <!-- check if variable exists --> <% if (locals.list) { %> <h2>Favorites</h2> <ul> <% for (var i = 0; i < list.length; i++) { %> <li> <%= list[i] %> </li> <% } %> </ul> <% } %> </body> </html> Now if you visit a URL like the ones above, you should see a similar result:

    Conclusion

    Thanks for reading this tutorial on Express routes! For more information on Node.js and Express you can check out these resources: TutorialsPoint Guide Express Routes Top 10 Mistakes Node.js Developers Make
    mrdaniel wrote this tutorial on 7/14/16 | javascript, nodejs, express
    Comments
    Log in to submit a comment.