devnotes.

Installation and First Application

Getting an Express app running takes only a handful of steps once Node.js and npm are installed on your machine.

Step 1: Create a project folder

mkdir bookstore-api
cd bookstore-api

Step 2: Initialize npm

npm init -y

This generates a package.json that tracks your project's metadata and dependencies.

Step 3: Install Express

npm install express

Express now appears under dependencies in package.json.

Step 4: Create the entry file

Create server.js in the project root:

const express = require("express");

const app = express();
const PORT = 4000;

app.get("/", (req, res) => {
    res.send("Welcome to the Bookstore API");
});

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
  • require("express") loads the framework.
  • express() creates the application instance.
  • app.get() registers a handler for GET requests to /.
  • app.listen() starts the HTTP server on the given port.

Step 5: Run it

node server.js

Visit http://localhost:4000 and you'll see the welcome message.

Step 6: Add more routes

app.get("/", (req, res) => {
    res.status(200).send("Bookstore API Home");
});

app.get("/catalog", (req, res) => {
    res.set("Content-Type", "text/html");
    res.status(200).send("<h1>Book Catalog</h1>");
});

app.post("/orders", (req, res) => {
    res.send("Order received");
});

Common HTTP verbs you'll use: GET, POST, PUT, PATCH, DELETE.

Step 7: Read data sent by the client

const express = require("express");
const app = express();

app.use(express.json());

app.post("/", (req, res) => {
    const { title } = req.body;
    res.send(`Added book: ${title}`);
});

app.listen(4000, () => console.log("Server running at http://localhost:4000"));

Test with a tool like Postman, Thunder Client, fetch(), or curl, sending a body such as { "title": "Atomic Habits" }.

Step 8: Different ways to respond

res.send("Plain text response");
res.json({ success: true, message: "Book added" });
res.status(201).send("Book Created");
res.set("Content-Type", "text/html");

Step 9: Serve static files

const path = require("path");

app.use("/static", express.static(path.join(__dirname, "public")));

Files placed in a public folder become reachable at http://localhost:4000/static/....

Step 10: Send a single file

app.get("/cover", (req, res) => {
    res.sendFile(path.join(__dirname, "public", "cover.jpg"));
});
Installation and First Application | DevNotes