Sikau

Node.js · Day 7 · about 30 min

Your first HTTP server

http.createServer, requests and responses.

Answer the web

Every website is a program somewhere answering requests. With Node's built-in http module you can write an HTTP server in a few lines: listen on a port, look at each request, send back a response.

createServer and listen

import http from "node:http";

const server = http.createServer((req, res) => {
  console.log(req.method, req.url);
  if (req.url === "/") {
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end("Welcome to Himalayan Café");
  } else {
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.end("Not found");
  }
});

server.listen(3000, () => console.log("Listening on http://localhost:3000"));

// Try it from the same program:
const home = await fetch("http://localhost:3000/");
console.log(home.status, await home.text());
const missing = await fetch("http://localhost:3000/pizza");
console.log(missing.status, await missing.text());
  • Status codes: 200 OK, 201 Created, 400 Bad Request, 401/403 not allowed, 404 Not Found, 500 server error.
  • req.method is GET, POST…; req.url is the path and query string.
  • Forget res.end() and the browser waits forever.

The rest of this lesson

  • What a request looks likeexplain
  • Content types matterexplain
  • Status?predict
  • Content typesmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 18 lessons of Node.js