NodeJS Learning Part 2

Swapnil Watkar
2 min readMar 11, 2022

Lets create our server to send data to front end application

Create a new project as discuss in part1
give the name myshopserver

create app.js file as entry point of our application.

lets say we have apis for products in our app.
Let us use end point as

http://localhost:3000/api/v1/products

Now product has id,name,cost,desc,image,brand

we will send the product details to front end via our server.
open app.js file and write the code below.

GET operation:

app.get(‘http://localhost:3000/api/v1/products',(req,res)=>{
const product = {
id:1,
name:’iphone’,
cost:’80000',
desc:’Apple iphone 13',
image:’some url’,
brand:’Apple’
}
res.send(product)
})

run application

open Postman and do get operation for our products api.
you will get JSON Object in response.

POST Operation:
post method needs data from front end, so we will send data to this method
in body.

add below code in app.js below get method.

app.post(‘http://localhost:3000/api/v1/products',(req,res)=>{
const newProduct = req.body;
console.log(newProduct)
res.send(newProduct)
})

goto postman ,select post method paste the endpoint url.
click body tab, select raw and json and pass the object below
{
id:2,
name:’Samsung’,
cost:’40000',
desc:’Android phone galaxy s22',
image:’some url’,
brand:’Samsung’
}
error: undefined.
why? request coming to our backend server do not recognised that object is JSON.
we need to tell our server what type of request is coming..
we need middleware (method) from express package this is express.json().

we declare this at top of get method
app.use(express.json()); →this will tell express that only json objects are accepted.
previously they use body parser app.use(bodyParser.json()), now it is depricated.

Logging Request:

In case we want to know what request come to our server, use morgon.
install morgon
npm install morgon
declare it on top
const morgon=require(‘morgon)

add the option for morgan
after middleware decleartion
app.use(morgon(‘tiny’));

run POST and GET from postman again see the output on console.

CODE:
const express = require('express');
const app = express();
const morgon=require('morgon)
app.use(express.json());
app.use(morgon('tiny'));
app.get('/',(req,res)=>{
res.send('happy learning')
})
app.get('http://localhost:3000/api/v1/products',(req,res)=>{
const product = {
id:1,
name:'iphone',
cost:'80000',
desc:'Apple iphone 13',
image:'some url',
brand:'Apple'
}
res.send(product)
})
app.post('http://localhost:3000/api/v1/products',(req,res)=>{
const newProduct = req.body;
console.log(newProduct)
res.send(product)
})
app.listen(3000, ()=>{
console.log('server is running on http://localhost:3000');
})

--

--

Swapnil Watkar

Hi ! I am a Software Engineer, experienced in Mobile and Web applications Also AWS Certified Solutions Architect — Associate