Handling GET requests in Node.js

  • Post category:Express
  • Reading time:2 mins read

This post will show how to handle GET requests in node.js.

How to Handle GET requests in Node.js

Now, let’s look at an example of GET requests in Node.js, and then I will explain this code.

Folder structure:

Code:

app.js

// app.js
const express = require('express');
const fs = require('fs');
const app = express();

const CountryData = JSON.parse(fs.readFileSync(`${__dirname}/Data/data.json`));

app.get('/hello', (req, res) => {
    res.status(200).json({
        status: 'success',
        data: {
            CountryData
        }
    });
});

const port = 8000;
app.listen(port, () => {
    console.log(`current port: ${port}`);
});

data.json

// data.json
[
  {
    "Country": "India",
    "Cities": ["Delhi", "Mumbai"]
  },
  {
    "Country": "USA",
    "Cities": ["New York", "Los Angeles"]
  },
  {
    "Country": "China",
    "Cities": ["Beijing", "Shanghai"]
  },
  {
    "Country": "Japan",
    "Cities": ["Tokyo", "Kyoto"]
  }
]

Code Explanation:

  • On line number 6 (app.js), fs.readFileSync is used for synchronously reading the content of the file at the specified path. JSON.parse parses the string content of the file into a JavaScript object.
  • On line number 8 (app.js), This sets up a route handler for GET requests to the /hello endpoint.
  • On line number 9 (app.js), res.status(200): Sets the HTTP status code to 200 (OK).
  • On line number 9 (app.js), app.listen(port, callback): Starts the server and listens on the specified port.
Share this