Docs
/
Cohort 1
/
Week 2
/
Express

Introduction to Express

In this lecture we covered about explanation of clinent-server modal and how to write an api using NodeJs and Express.

Client Server Model

  • Below is a diagram explaining how our client-side makes requests to the server-side, with the assistance of HTTP requests.

  • Below is a diagram that illustrates the four main breakdowns of the backend.

  • Below is a diagram that illustrates the five main breakdowns of the HTTP Server.

How to write an API.

  • Step 1- Open terminal in Vs Code write below command to initialize your Node.js Project.

    npm init -y

    and hit enter, there will be package.json file will be created inside your folder.

  • if there is any error-google it.
  • Step 2- Install express by running this command on terminal:

npm i express
  • Step 3- Create an Index.js file in root directory and paste the below code.
// biolerplate code
const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})
  • step 4 run your server using below command in your terminal.
node index

Request Method, URL Route and Query/Params/Headers/Body

  • In Below code there is 2 route created in which -

route 1 - \ which is just prinitng a statement.

route 2- \handleSum which is taking input in query parameter ?counter=10 and returning sum from 0 to that number.

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

function calculateSum(counter){
    var sum=0;
    for(var i=0;i<=counter;i++){
        sum=sum+i;
    }
    return sum;
}

function handleFirstRequest(req,res){
    var lastIndex=req.query.counter
    var calculatedSum=calculateSum(lastIndex)
    var answer="Calculated Sum is : "+calculatedSum
    console.log(answer);
    res.send(answer);
}

app.get('/handlesum',handleFirstRequest)

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})
  • On running above code we will having below 2 route.
http://localhost:3000/
http://localhost:3000/handlesum?counter=100

  • url - http://localhost:3000/ and http://localhost:3000/handlesum?counter=100
  • route - / and /handlesum
  • method - Get
Last updated on February 12, 2024