Build a small JSON endpoint

Lesson 2 of 4 · 1 min read

Return your first response

Separate a request handler from the process that listens on a port.

Demo lesson · not author-approved.

Write the handler

Create handler.js:

export function handler(request, response) {
  response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  response.end(JSON.stringify({ message: 'Hello, reader!' }));
}

An HTTP response has a status, headers, and a body. Here, status 200 signals success and the content type tells the client to interpret the body as JSON.

Start a local server

Create server.js:

import { createServer } from 'node:http';
import { handler } from './handler.js';

const server = createServer(handler);
server.listen(3000, '127.0.0.1', () => {
  console.log('Open http://127.0.0.1:3000/hello');
});

Run npm start, then open http://127.0.0.1:3000/hello. You should see the greeting. The loopback address keeps this exercise local rather than listening on every network interface.

Notice what is missing

Every route and every method currently receives the same greeting. /missing works just like /hello. The handler also ignores query parameters.

That is a useful first checkpoint, but not a useful endpoint contract. In the next lesson you will make those boundaries explicit.

Stop the server with Ctrl+C before editing. If port 3000 is already occupied, close the other local process or change the port and use the matching browser URL.