DEV Community

Cover image for You need to know about req and res objects to build an API in Node.js using Express.js
Luiz Calaça
Luiz Calaça

Posted on • Updated on

You need to know about req and res objects to build an API in Node.js using Express.js

Hi, Devs!

We can have req and res objects into Express.js, they are used to handle the request and response using HTTP protocol and its verbs and status code.

page not found 404 status code HTTP

Remember! We have some HTTP verbs and they can do some actions and return some status code.

  • Informational responses (100–199)
  • Successful responses (200–299)
  • Redirection messages (300–399)
  • Client error responses (400–499)
  • Server error responses (500–599)

Let's assume a bit code to show Express.js and its response (res) and request (req) object:

const express = require('express');
const cors = require('cors');
const app = express();
const bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: false }))'/example', handleCreate); //save with req.body data
app.get('/example/search/', handleSearch); //find the data
app.get('/example/:id', handleFindById); //find by an id

app.listen(3000, () => {
  console.log('Running on 3000');
Enter fullscreen mode Exit fullscreen mode

Let's see the examples:

It's populated when you use body-parsing middleware such as body-parser. And response here is just send the result from the database.

endpoint:'/example', handleCreate);
http verb: POST
URL example: http://localhost:3000/example
Status: 201

async function handleCreate(req, res) {
  const {name, age} = req.body
  const result = await database.create(name, age)
Enter fullscreen mode Exit fullscreen mode

if you have the route /example/:id, then the “id” property is available as ou using destructuring like below. And here the response is sending the status and the data in JSON format.

endpoint: app.get('/example/:id', handleFindById);
http verb: GET
URL example: http://localhost:3000/example/1
Status: 200
Response: res.status(200).json(result)

async function handleFindById(req, res) {
  const { id } = req.params //or
  const result = await database.findById(id)
Enter fullscreen mode Exit fullscreen mode

This property is an object containing a property for each query string parameter in the route, as well using when we have more than one parameter to share on url, because we can get the value of ?name=Calaca&age=32&live=Brazil&leve=senior. And the response here is sending status 200 and result from database.

endpoint: app.get('/example/search', handleSearch);
http verb: GET
URL example: http://localhost:3000/example/search?name=Calaca
Status response: 200

async function handleSearch(req, res) {
  const {name} = req.query
  const result = await database.findByName(name)
Enter fullscreen mode Exit fullscreen mode


Simple and effective.


Top comments (1)

hajayandi_jeandedieu_8c profile image
Hajayandi Jean De Dieu

good support