Express JS: What is Basic Routing ?

Express JS: What is Basic Routing ?

If you curios about Express JS, join with me and learn it.

ยท

2 min read

Hola guys , In this section we will go through the basic routing in Express JS.

let's see the basic explanation Routing in Express JS .

Basic routing

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Each route can have one or more handler functions, which are executed when the route is matched.

Route definition takes the following structure:

app.METHOD(PATH, HANDLER_FUNCTION)
  • App is an instance of express.
  • METHOD is an HTTP request method, in lowercase. example : get,post,put,etc .
  • PATH is a path on the server.
  • HANDLER_FUNCTION is the function executed when the route is matched.

lets see some examples for routing in Express JS .

HANDLER_FUNCTION has two inputs.

  • req - known as request , has all data of an api call by some user.
  • res - known as response , this variable have result of an request given by some user.

res.send(data) includes the data in response of an api .

you can write your logic in HANDLER_FUNCTION.

// A route with get method , "/" endpoint.
app.get('/', (req, res) => {
  res.send('Hello World!')
})

// A route with post method , "/" endpoint.
app.post('/', (req, res) => {
  res.send('Got a POST request')
})

// A route with put method , "/user" endpoint.
app.put('/user', (req, res) => {
  res.send('Got a PUT request at /user')
})

Now, we have created some API

How to test these APIs ?

Download Postman HERE

Postman is the software, where we can test our api .

Here, I will give the full 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}`)
})

Now , Run the app using the following command.

node server.js

and move to Postman to test API .

image.png

you will get a result as Hello World! .

Thank you guys, please subscribe to my blog. so that you will get all my posts and blogs.

Did you find this article valuable?

Support HARRISH G by becoming a sponsor. Any amount is appreciated!

ย