MDN self-hosted library · e01.org

Express/Node introduction

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
   // Load HTTP module
   import http from "node:http";

   const hostname = "127.0.0.1";
   const port = 8000;

   // Create HTTP server
   const server = http.createServer((req, res) => {
     // Set the response HTTP header with HTTP status and Content type
     res.writeHead(200, { "Content-Type": "text/plain" });

     // Send the response body "Hello World"
     res.end("Hello World\n");
   });

   // Prints a log once the server starts listening
   server.listen(port, hostname, () => {
     console.log(`Server running at http://${hostname}:${port}/`);
   });
js
import express from "express";

const app = express();
const port = 3000;

app.get("/", (req, res) => {
  res.send("Hello World!");
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}!`);
});
js
import express from "express";

const app = express();
js
export function area(width) {
  return width * width;
}

export function perimeter(width) {
  return 4 * width;
}
js
import { area } from "./square.js";

console.log(`The area of a square with a width of 4 is ${area(4)}`);
js
import * as square from "./square.js";

console.log(
  `The perimeter of a square with a width of 4 is ${square.perimeter(4)}`,
);
js
export default function area(width) {
  return width * width;
}
js
import squareArea from "./square.js";

console.log(squareArea(4));
js
console.log("First");
console.log("Second");
js
setTimeout(() => {
  console.log("First");
}, 3000);
console.log("Second");
js
app.get("/", (req, res) => {
  res.send("Hello World!");
});
js
app.all("/secret", (req, res, next) => {
  console.log("Accessing the secret section…");
  next(); // pass control to the next handler
});
js
// wiki.js - Wiki route module

import { Router } from "express";

const router = Router();

// Home page route
router.get("/", (req, res) => {
  res.send("Wiki home page");
});

// About page route
router.get("/about", (req, res) => {
  res.send("About this wiki");
});

export default router;
js
import wiki from "./wiki.js";

// …
app.use("/wiki", wiki);
js
import express from "express";
import logger from "morgan";

const app = express();
app.use(logger("dev"));
// …
js
import express from "express";

const app = express();

// An example middleware function
function middlewareFunction(req, res, next) {
  // Perform some operations
  next(); // Call next() so Express will call the next middleware function in the chain.
}

// Function added with use() for all routes and verbs
app.use(middlewareFunction);

// Function added with use() for a specific route
app.use("/some-route", middlewareFunction);

// A middleware function added for a specific HTTP verb and route
app.get("/", middlewareFunction);

app.listen(3000);
js
app.use(express.static("public"));
js
app.use(express.static("public"));
app.use(express.static("media"));
js
app.use("/media", express.static("public"));
js
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send("Something broke!");
});
js
import { MongoClient } from "mongodb";

const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();
    const db = client.db("animals");
    const mammals = await db.collection("mammals").find().toArray();
    console.log(mammals);
  } finally {
    await client.close();
  }
}

run().catch(console.error);
js
import express from "express";
import path from "node:path";

const app = express();

// Set directory to contain the templates ('views')
app.set("views", path.join(import.meta.dirname, "views"));

// Set view engine to use, in this case 'some_template_engine_name'
app.set("view engine", "some_template_engine_name");
js
app.get("/", (req, res) => {
  res.render("index", { title: "About dogs", message: "Dogs rock!" });
});