A simple HelloWorld get route in NodeJS (with Express)
Let us start from basics to understand better.
What is a route?
Routes are the ways to handle user navigation to different URLs. There are various HTTP request methods like post, put, delete, merge, patch etc to design your application. ExpressJS provides a beautiful documentation along with examples. Refer ExpressJS documentation here.
How to create a NodeJS project
pre-requisites
- Download NodeJS here and install it.
- You can write code in any text editor. I prefer
Visual Studio Code
but there are options like sublime text, Atom, aptana studio etc.
How to start
- create a folder in your repository
- Open terminal and navigate to the folder you created.
- execute
npm init
, which creates package.json file.package.json
file is like a manifest for your application and contains npm packages information which are used in the application development. - execute
code package.json
, to open the package.json file in your visual studio code. - Install the express dependency as shown below
npm i express --save
- Create index.js file to write your code
Why ExpressJS
It is a small pre-built NodeJS framework which is very muchful helpful as it creates server-side web applications faster and smarter.
NodeJS Hello world program (index.js)
const express = require('express');
const server = express();
server.get('/', ( req, res) => {
res.send("Hello World!!");
});
server.listen(5000, () => console.log("server started on 5000"));
How to run your code
- switch to your terminal again or you can open terminal in your VS code itself.
- Execute the below command
node index.js
How to Test
- Hit the url
http://localhost:5000/
in your browser to see theHello World!!
message