Deviopath › Node.js

JSON Response

Easy · HTTP

In a plain Node HTTP server you send JSON by calling res.writeHead(status, headers) and then res.end(JSON.stringify(data)).

Write a function jsonResponse(data, status = 200) that returns a plain object describing that response:

- status: the status code (default 200)

- headers: { "Content-Type": "application/json; charset=utf-8" }

- body: data converted with JSON.stringify

Next: Safe JSON Parse