EN
Node.js - send JSON in response (default HTTP server)
3
points
In this article, we would like to show you how to send JSON in response using Node.js.
Quick solution:
const app = http.createServer((req, res) => {
const object = {
id: 1,
name: 'John'
};
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(object));
});
Practical example
In this example, we use setHeader() method to set response header to Content-Type: application/json. Then, using JSON.stringify() method we can send the JSON as a response using end() method.
const http = require('http');
const app = http.createServer((req, res) => {
const object = {
id: 1,
name: 'John'
};
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(object));
});
app.listen(8080, () => console.log('Server started on port 8080.'));
Hint: use Express.js to handle requests in different paths, .e.g. is available here.