JSON response
- Node.js course
- Intermediate
- Lesson 16/116
- 5 min
Learn to return JSON-formatted responses.
JSON response
In an API the response is usually sent in JSON format. In Node.js JSON.stringify(object) converts an object to a JSON string. Example: JSON.stringify({ msg: "Hello" }) gives {"msg":"Hello"}.
To make the browser interpret the response as JSON you must set the content type: res.setHeader("Content-Type", "application/json"). Then send with res.end(JSON.stringify(data)). Example: res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify({ msg: "Hello" }));. This is the standard response format of REST APIs; the client easily converts it to an object with JSON.parse.
The content type header
When sending a JSON response the Content-Type header is important. The value application/json marks the response as JSON; the client parses it automatically.
You add the header with res.setHeader: res.setHeader("Content-Type", "application/json"). This call must come before res.end, because headers are sent before the response body. A wrong content type (e.g. text/plain) makes JSON appear as plain text; some clients cannot parse it. The right header ensures the API is used safely.
Practice Send a JSON response
Import the http module. Create a server with createServer. Inside the handler call res.setHeader("Content-Type", "application/json") and respond with res.end(JSON.stringify({ msg: "Hello" })). The ready-made code below starts the server and sends a request.
Starter code
// Import the http module and create a server
// write here
server.listen(3000, () => {
http.get("http://localhost:3000/", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});Sample solution
const http = require("http");
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ msg: "Hello" }));
});
server.listen(3000, () => {
http.get("http://localhost:3000/", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});Expected output
Yanıt: {"mesaj":"Merhaba"}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the JSON.stringify call
res.end(JSON.____({ mesaj: "Merhaba" }));
res.end(JSON.stringify({ mesaj: "Merhaba" }));
Explanation: JSON.stringify converts an object to a string.
2 Match each piece to its role
| Term | Meaning |
|---|---|
JSON.stringify |
Converts object to string |
res.setHeader |
Adds a header |
application/json |
JSON content type |
res.end |
Sends the response |
3 What should Content-Type be for a JSON response?
res.setHeader("Content-Type", "?")- text/plain
- text/html
- text/string
- application/json Correct answer
Explanation: application/json marks the response as JSON.