การกำหนดเส้นทางและมิดเดิลแวร์ใน Express
เชี่ยวชาญการกำหนดเส้นทางของ Express เพื่อสร้างจุดเชื่อมต่อ API และนำมิดเดิลแวร์มาใช้ประมวลผลคำขอ
การกำหนดเส้นทางและมิดเดิลแวร์ใน Express เป็นบทเรียน Node.js Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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 ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Node.js Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การกำหนดเส้นทางและมิดเดิลแวร์ใน Express”
เชี่ยวชาญการกำหนดเส้นทางของ Express เพื่อสร้างจุดเชื่อมต่อ API และนำมิดเดิลแวร์มาใช้ประมวลผลคำขอ คุณปฏิบัติ Node.js Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Node.js Backend Development Bootcamp หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Node.js Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การกำหนดเส้นทางและมิดเดิลแวร์ใน Express” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Node.js Backend Development Bootcamp นี้ได้ไหม
ได้ บทเรียน Node.js Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- พื้นฐานกรอบงาน Express.js
- การกำหนดเส้นทางและมิดเดิลแวร์ใน Express
- การออกแบบจุดเชื่อมต่อ RESTful API
- การจัดการข้อมูลคำขอ: เนื้อหา คิวรี และพารามิเตอร์