← Back to Node.js Course | Chapter 7: Express.js Basics | Lesson 3 of 7

Routes

Routes map a method and a URL path to the function that handles it.

In this page:

  1. Routes
Syntax
javascript
app.get('/path', (req, res) => {
  res.send('response');
});
app.post('/path', handler);
app.put('/path/:id', handler);
app.delete('/path/:id', handler);

Routes

Define routes with app.get, app.post, app.put and app.delete. Paths can contain parameters such as /users/:id available in req.params. Routes are checked in the order defined and the first that responds wins.

Note: Use express.Router to group related routes in separate files.

Example: Routes

bash
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("home"));
app.get("/users/:id", (req, res) => res.json({ id: req.params.id }));
app.post("/users", express.json(), (req, res) => res.status(201).json(req.body));
app.listen(3000, () => console.log("listening on 3000"));
// GET /users/42  ->  {"id":"42"}

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Defining a catch-all before specific routes
  2. Forgetting to respond
  3. Using the wrong HTTP method
Chapter Summary
  • app.METHOD(path, handler)
  • :id creates params
  • Order matters
  • Router groups routes
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.