Course Node.js Backend Development

Your First Server

Node.js Basics Preview

A web server

const http = require("node:http");\n\nconst server = http.createServer((req, res) => {\n  res.writeHead(200, { "Content-Type": "text/plain" });\n  res.end("Hello from Node!");\n});\n\nserver.listen(3000, () => {\n  console.log("Server running on http://localhost:3000");\n});

Run it

node server.js\n# open http://localhost:3000

Reading the request

const server = http.createServer((req, res) => {\n  console.log(req.method, req.url);\n  if (req.url === "/") {\n    res.end("Home");\n  } else {\n    res.writeHead(404);\n    res.end("Not found");\n  }\n});

Reading JSON body

let body = "";\nreq.on("data", (chunk) => (body += chunk));\nreq.on("end", () => {\n  const data = JSON.parse(body);\n  console.log(data);\n});

Why Express?

The raw http module gets verbose fast. Express adds routing, middleware, helpers and structure on top of it.

The flow

request → server → handler → response\n                 ↑\n            route match
Tip: Raw http is great to understand once — then use Express for real work. It is the industry standard.

This is a free preview lesson

Enroll in the Node.js Backend Development to unlock every lesson, lesson PDF guides, quizzes and your certificate - and start creating your own pieces today.


Discussion

Free preview lesson