Node.js
JSON response
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.
Exercise 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.
Show example 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(); });
});
});
Test yourself
-
Complete the JSON.stringify call
res.end(JSON.____({ mesaj: "Merhaba" }));
Show answer
res.end(JSON.stringify({ mesaj: "Merhaba" }));
-
Match each piece to its role
- JSON.stringify
- Converts object to string
- res.setHeader
- Adds a header
- application/json
- JSON content type
- res.end
- Sends the response
-
What should Content-Type be for a JSON response?
res.setHeader("Content-Type", "?")
- text/plain
- text/html
- text/string
- application/json
Show answer
application/json — application/json marks the response as JSON.
Next lesson: Query string