0Pricing
Node.js Backend Development Bootcamp · 课时

Express 中的路由与中间件

掌握 Express 路由以定义 API 端点,并实现用于请求处理的中间件。

Express 中的路由与中间件 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Routing Your Express API

Welcome back! In this lesson, we'll dive into routing and middleware in Express. These are core concepts for building powerful and organized web applications.

Routing helps your server understand what to do when it receives different requests, like showing a user profile or saving new data.

Defining Basic Routes

A route tells your Express app how to respond to a specific type of request to a particular URL path. You define routes using methods like app.get(), app.post(), app.put(), and app.delete().

Each route method takes a path and a handler function that executes when the route is matched.

First GET Route Example

Let's create a simple GET route that responds to requests at the root URL (/). This is often your homepage or a basic API status check.

The handler function receives req (request) and res (response) objects.

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

app.get('/', (req, res) => {
  res.send('Hello from our Express API!');
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

Handling Dynamic Route Parameters

Often, you need to capture dynamic values from the URL, like a user's ID. This is done with route parameters, denoted by a colon (:) in the path.

You can access these parameters through the req.params object in your route handler.

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

app.get('/users/:userId', (req, res) => {
  const userId = req.params.userId;
  res.send(`You requested user ID: ${userId}`);
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

What is Middleware?

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.

They can:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.

The 'next()' Function

The key to middleware is the next() function. If a middleware function does not end the request-response cycle (e.g., by calling res.send()), it must call next() to pass control to the next middleware function or route handler.

If next() is not called, the request will be left hanging.

Application-level Middleware

You can apply middleware globally to all requests using app.use(). This is great for tasks like logging, parsing JSON bodies, or setting common headers.

Let's create a simple logger that runs for every incoming request.

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

// Application-level middleware
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next(); // Don't forget to call next()
});

app.get('/', (req, res) => {
  res.send('Check your server console for the log!');
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

Route-level Middleware

Sometimes, you only want middleware to run for specific routes. You can apply route-level middleware by passing it as an argument before the route handler function.

You can even chain multiple middleware functions for a single route.

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

// A simple authentication middleware
const isAuthenticated = (req, res, next) => {
  if (req.headers.authorization === 'Bearer mysecrettoken') {
    next(); // User is authenticated, proceed
  } else {
    res.status(401).send('Unauthorized: Invalid token');
  }
};

// Apply isAuthenticated middleware only to this route
app.get('/dashboard', isAuthenticated, (req, res) => {
  res.send('Welcome to the protected dashboard!');
});

app.get('/', (req, res) => {
  res.send('Public content here.');
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

Common Middleware Uses

Middleware is incredibly versatile. Here are some common use cases:

  • Authentication/Authorization: Checking user credentials or permissions.
  • Logging: Recording request details for debugging or monitoring.
  • Body Parsing: Extracting JSON or URL-encoded data from request bodies (e.g., express.json()).
  • Error Handling: Catching and responding to errors (special middleware type).
  • Input Validation: Ensuring request data meets specific criteria.

Middleware & Routing Check

Let's test your understanding of Express routing and middleware!

Recap: Routing & Middleware

Great job! You've learned how Express uses routing to direct requests to specific handlers based on URL paths and HTTP methods.

You also mastered middleware, powerful functions that can intercept and process requests at various stages, either globally with app.use() or for specific routes. Understanding these concepts is fundamental to building robust Express applications!

常见问题解答

「Express 中的路由与中间件」课时是免费的吗?

是的 — 「Express 中的路由与中间件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。

「Express 中的路由与中间件」这节课中我会学到什么?

掌握 Express 路由以定义 API 端点,并实现用于请求处理的中间件。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Node.js Backend Development Bootcamp 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「Express 中的路由与中间件」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?

能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Express.js 框架基础
  2. Express 中的路由与中间件
  3. 设计 RESTful API 端点
  4. 处理请求数据:正文、查询与参数
← 返回 Node.js Backend Development Bootcamp