Hello all. In this blog, I am explaining how to perform routing with Node JS. Routing is one of the most important parts of any Web framework since it defines how our application should handle all the HTTP requests by the client.


Table of Content

  1. Create a Node JS Project
  2. Creating a simple Server with Express JS
  3. Organizing Routes in the Main File
  4. Organizing all routes in a Separate file
  5. Installing Logger Middleware — Morgan

  1. Creating a Node JS Project

Create a new directory and initialize node with the command npm init.

mkdir helloworld
cd helloworld/
npm init -y

After executing the command, a package.json file generated in the project’s root directory. This holds all the metadata relevant to the project.

On this file, we see something called scripts. This is the place where we add our own commands for the project. I am creating a new command which starts my server when I type npm start. The script tells node that it should run the command node index.js every time when I execute the command npm start.

package.json

"scripts": {
   "start": "node index.js",
   "test": "echo \"Error: no test specified\" && exit 1"
},

2. Creating a simple Server with Express JS

Now let’s create our server. Here we are creating our server using Express.js. Express JS is an open-source web framework for node JS. It is designing for building web apps and APIs. The below command installs express to our project.

npm install express --save

Express - Node.js web application framework

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and…

expressjs.com

We are using express to create a new server that will be running on the port 8000. Also for the demonstration, I am creating a route that returns hello world.

index.js

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});
app.listen(8000, function () {
  console.log('Listening to Port 8000');
});

Now start the server, you should see hello world being displayed in the browser.

npm start

#joan-louji #nodejs #routing #expressjs #express-routing #express

Node JS — Router and Routes
1.35 GEEK