#4 Pure NodeJs: return JSON (Part 4)

basharosman

Bashar

Posted on February 7, 2024

#4 Pure NodeJs: return JSON (Part 4)

In this tutorial we will continue the Pure NodeJs Series by showing how to serve json data.

programs and versions:
nodejs: v18.19.0
npm: v10.2.3
vscode: v1.85.2

should work on any nodejs > 14

we will use code similer to the code in the previews article #2 Pure NodeJs: simple server (Part 2).

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end('<h1>Hello World!</h1>');
});

const PORT = 2121;
server.listen(PORT, 'localhost', () => {
  console.log(`server run on port ${PORT}`);
});

Enter fullscreen mode Exit fullscreen mode

this code will return html to the browser page if we want to return json/object data we can use mock data like this:

const data = [
  {
    country: "United States",
    city: "New York",
    timezone: "America/New_York",
    currency: "USD"
  },
  {
    country: "United Kingdom",
    city: "London",
    timezone: "Europe/London",
    currency: "GBP"
  },
  {
    country: "France",
    city: "Paris",
    timezone: "Europe/Paris",
    currency: "EUR"
  },
  {
    country: "Japan",
    city: "Tokyo",
    timezone: "Asia/Tokyo",
    currency: "JPY"
  },
  {
    country: "Australia",
    city: "Sydney",
    timezone: "Australia/Sydney",
    currency: "AUD"
  }
]
Enter fullscreen mode Exit fullscreen mode

to return this data we need to change the 'Content-Type'to be 'application/json' like this code.

  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(data));
Enter fullscreen mode Exit fullscreen mode

Notice that we've utilized JSON.stringify to encapsulate the data. This step is crucial because our intention is to return the data as a string. Additionally, we include 'Content-Type': 'application/json' to specify that the response for the request will be in JSON format, not as a string document.

the complete code:

//server.js
const http = require('http');
const data = [
  {
    country: 'United States',
    city: 'New York',
    timezone: 'America/New_York',
    currency: 'USD',
  },
  {
    country: 'United Kingdom',
    city: 'London',
    timezone: 'Europe/London',
    currency: 'GBP',
  },
  {
    country: 'France',
    city: 'Paris',
    timezone: 'Europe/Paris',
    currency: 'EUR',
  },
  {
    country: 'Japan',
    city: 'Tokyo',
    timezone: 'Asia/Tokyo',
    currency: 'JPY',
  },
  {
    country: 'Australia',
    city: 'Sydney',
    timezone: 'Australia/Sydney',
    currency: 'AUD',
  },
];
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(data));
});

const PORT = 2121;
server.listen(PORT, 'localhost', () => {
  console.log(`server run on port ${PORT}`);
});


Enter fullscreen mode Exit fullscreen mode

To start the server and open the browser localhost:2121.

node server.js
Enter fullscreen mode Exit fullscreen mode

Conclusion:

In this article we show you how to serve data as JSON format
note you can save the data in data.json file and serve the Json data from the file like we did in previews article #3 Pure NodeJs: return html file (Part 3).

In the upcoming article I'll guide you through the process of serving different data types in different routes

💖 💪 🙅 🚩
basharosman
Bashar

Posted on February 7, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Day 5 of NodeJS||REPL Part 1
webdev Day 5 of NodeJS||REPL Part 1

July 27, 2024

#4 Pure NodeJs: return JSON (Part 4)
webdev #4 Pure NodeJs: return JSON (Part 4)

February 7, 2024