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}`);
});
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"
}
]
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));
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}`);
});
To start the server and open the browser localhost:2121.
node server.js
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
Top comments (0)