JavaScript

Introduction to Node.js and Express

What is Node.js?

Node.js lets you run JavaScript outside the browser — on a server. This means you can use one language for both your frontend and backend.

Your First Server

Node ships with an http module, but most real projects use the Express framework for a simpler API.

npm init -y npm install express
const express = require("express"); const app = express(); app.get("/", (req, res) => { res.send("Hello from Express!"); }); app.listen(3000, () => console.log("Server running on port 3000"));

Routes and Parameters

app.get("/tutorials/:id", (req, res) => { res.json({ id: req.params.id, title: "Sample Tutorial" }); });

Handling JSON Request Bodies

app.use(express.json()); app.post("/tutorials", (req, res) => { const { title } = req.body; res.status(201).json({ message: `Created: ${title}` }); });

Middleware

Middleware functions run between the request and your route handler — useful for logging, authentication, and validation.

app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); });

Practice Exercise

Build a small Express API with a GET route that returns a list of tutorials as JSON, and a POST route that accepts a new tutorial title.

Leave a Reply

Your email address will not be published. Required fields are marked *