Node.js
Serve JSON from a minimal Node HTTP server
Use node:http to create a small HTTP server, set the response content type, and end the response with serialized JSON. Every request path should receive an explicit response.
Worked example
Node.js example · save as example.mjs and run node example.mjs
import {createServer} from "node:http";
const server = createServer((request, response) => {
response.writeHead(200, {"content-type": "application/json; charset=utf-8"});
response.end(JSON.stringify({ok: true}));
});
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
try {
const response = await fetch(`http://127.0.0.1:${server.address().port}/`);
console.log((await response.json()).ok);
} finally { await new Promise(resolve => server.close(resolve)); }How it works
Port zero lets the operating system choose an available local port. The example requests its own loopback server, reads the JSON, and closes the server in finally. A real application would normally keep the server open until shutdown.
Limits and mistakes
This is a minimal local example, not a production API framework. It does not validate routes, authenticate callers, enforce request-size limits, or configure TLS. Handle listening errors and operational concerns before exposing a server publicly.
Check the result
Expect true and a process that exits after closing the server. Check status and content type as well as the JSON body in your application’s own integration checks.
Sources
Reference documentation for the behavior used in this guide: