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:
xxxxxxxxxx
1
const app = http.createServer((req, res) => {
2
const object = {
3
id: 1,
4
name: 'John'
5
};
6
res.setHeader('Content-Type', 'application/json');
7
res.end(JSON.stringify(object));
8
});
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.
xxxxxxxxxx
1
const http = require('http');
2
3
const app = http.createServer((req, res) => {
4
const object = {
5
id: 1,
6
name: 'John'
7
};
8
res.setHeader('Content-Type', 'application/json');
9
res.end(JSON.stringify(object));
10
});
11
12
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.