22/180: Create Hello World API using NodeJS

Navneet Ojha
2 min readApr 11, 2021

My assumptions are you have basic knowledge of JavaScript.

Getting Started

To get started create a new folder and call it hello_world.

$ mkdir myapp
$ cd myapp
//if windows users they can directly create the folder, and after getting inside the folder they can open the command prompt from there, which will get them into the same folder.

In your myapp folder create a new file called app.js

$ touch app.js
//if windows users they can directly create a file by write clicking

The next thing for us to do is to install Node. you can install node here. After node has been installed then we’ll install express with npm.

npm init

Click the return key repeatedly for every questions asked of you on the command line. This creates a package.json file in your myapp folder. The file contains references for all npm packages you have downloaded to your project. The command will prompt you to enter a number of things.

Install Dependencies

//server, Allows to set up middlewares to respond to HTTP Requests.
//Defines a routing table which is used to perform different actions //based on HTTP Method and URL.
//Allows to dynamically render HTML Pages based on passing arguments to templates.
npm install express —-save
//cors so your api can be access by other apps
npm install -g cors

Setup The App And Create Our First Endpoint

Now let’s get started creating our hello_world app

//Import cors
import cors from 'cors';
//Require moduleconst express = require('express');// Express Initializeconst app = express();//Required module
//enable cors
app.use(cors); /* NEW */
//to allow express server to use cors middleware
app.use(express.json());
You can also define particular origins like this, instead of allowing all
// Add a list of allowed origins.
// If you have more origins you would like to add, you can add them //to the array below.
//const allowedOrigins = ['http://localhost:3000'];

//const options: cors.CorsOptions = {
// origin: allowedOrigins
//};
//app.use(cors(options));

Start Server

//Require moduleconst express = require('express');// Express Initializeconst
app = express();
const port = 8000;
app.listen(port,()=> {console.log('listen port 8000');})

Create API

//create api
app.get('/hello_world', (req,res)=>{res.send('Hello World');})

You can check this on postman or directly on browsers by hitting this API

http://localhost:8000/hello_word

It will print hello world.

--

--

Navneet Ojha

I am Indian by birth, Punjabi by destiny. Humanity is my religion. Love to eat, travel, read books and my million dreams keep me alive.