22/180: Create Hello World API using NodeJS

Getting Started

$ 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.
$ touch app.js
//if windows users they can directly create a file by write clicking
npm init

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

//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');})

--

--

--

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.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to access MongoDB from Node.js

Create an Audio Visualizer with React and Canvas: Part 1 of 3

Using React within a Design System

Async JavaScript, a Pocket Reference

Announcing styled-components v5: Beast Mode 💪🔥

Infinite Board for Drag-And-Drop Notes using Angular

Learning Typescript as a Beginner Javascript Programmer

How to add a hamburger navigation menu in React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Navneet Ojha

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.

More from Medium

Using express-session middleware and MongoDB session store in Nodejs for production apps

Setup PostGres with Node.js & Knex

Stepwise Guide to Node.js Authentication with Express and Knex

Deploy Nodejs Backend App on Digital Ocean