การพัฒนามิดเดิลแวร์ Express แบบกำหนดเอง
เขียนฟังก์ชันมิดเดิลแวร์ Express ของคุณเองเพื่อเพิ่มความสามารถและทำให้การประมวลผลคำขอคล่องตัวขึ้น
การพัฒนามิดเดิลแวร์ Express แบบกำหนดเอง เป็นบทเรียน Node.js Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Node.js Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What is Custom Middleware?
In Express.js, middleware functions are like a chain of helpers that process incoming requests before they reach your final route handler.
- They have access to the request (
req) and response (res) objects. - They can modify these objects, end the request-response cycle, or pass control to the next middleware.
- Custom middleware allows you to add specific functionality tailored to your application's needs, such as logging, authentication, or data parsing.
The Middleware Signature
Every Express middleware function follows a specific signature: (req, res, next).
req(request): The incoming HTTP request object.res(response): The HTTP response object that Express sends back.next: A function that, when called, passes control to the next middleware function in the stack. If you don't callnext(), the request-response cycle stops, and no further middleware or route handlers will execute.
Your First Logger Middleware
Let's create a simple custom middleware that logs details of every incoming request to the console. This helps in debugging and monitoring.
Try running the code and then accessing http://localhost:3000 in your browser. Check the console output!
const express = require('express');
const app = express();
const port = 3000;
// Custom logging middleware
const requestLogger = (req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next(); // Pass control to the next middleware/route handler
};
// Apply the custom middleware globally
app.use(requestLogger);
// Define a simple route
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
// Start the server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});Applying Middleware: Global vs. Route
You can apply middleware at different levels:
- Globally (Application-level): Using
app.use(middlewareFunction)applies the middleware to ALL incoming requests. - Route-specific: You can apply middleware to specific routes or groups of routes by passing it as an argument before the route handler.
This flexibility allows you to execute logic only where it's needed.
Passing Data Downstream
A powerful feature of middleware is its ability to add properties to the req object. These properties then become accessible to all subsequent middleware functions and the final route handler in the request-response cycle.
This is extremely useful for things like attaching user information after authentication, or parsed data before reaching the main logic.
Example: Attaching User Data
Here's how you might attach a mock user object to the request. In a real application, this data would come from a database or a decoded JSON Web Token (JWT).
Notice how the /profile route handler can directly access req.user because the attachUserInfo middleware ran first.
const express = require('express');
const app = express();
const port = 3000;
// Middleware to attach user info (mock data)
const attachUserInfo = (req, res, next) => {
req.user = { id: '123', name: 'Alice', role: 'admin' };
console.log('User info attached to request.');
next();
};
// Apply the middleware globally
app.use(attachUserInfo);
// Route that uses the attached user info
app.get('/profile', (req, res) => {
res.send(`Welcome, ${req.user.name}! Your role is: ${req.user.role}`);
});
app.get('/', (req, res) => {
res.send('Home page (no user info explicitly needed here)');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});Building Middleware Chains
You can chain multiple middleware functions together. Express executes them in the order they are defined. Each middleware must call next() to pass control to the next one.
- This allows you to break down complex request processing into smaller, manageable, and reusable functions.
- For example, you could have a middleware for authentication, then one for logging, then one for parsing, all before your final route handler.
Conditional Middleware Execution
Sometimes you only want middleware to run under certain conditions. You can achieve this by:
- Route-specific application: As seen, applying middleware directly to
app.get(),app.post(), etc. - Internal logic: Adding conditional checks (
ifstatements) inside the middleware itself. - Custom wrapper functions: Creating a function that returns a middleware based on parameters.
Practical: Request Timer Middleware
Let's build a middleware that measures how long it takes for a request to be processed and a response to be sent. This is very useful for performance monitoring.
This example uses res.on('finish', ...) to execute code AFTER the response has been sent to the client.
const express = require('express');
const app = express();
const port = 3000;
// Middleware to measure request duration
const requestTimer = (req, res, next) => {
const start = Date.now(); // Record start time
res.on('finish', () => { // Listen for the response 'finish' event
const end = Date.now(); // Record end time
const duration = end - start;
console.log(`${req.method} ${req.originalUrl} took ${duration}ms`);
});
next(); // Pass control
};
// Apply the timer middleware
app.use(requestTimer);
// Define a route that simulates some work
app.get('/slow', (req, res) => {
setTimeout(() => {
res.send('This was a slow response!');
}, 500); // Simulate 500ms delay
});
app.get('/', (req, res) => {
res.send('Hello, fast world!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});Middleware Function Quiz
Consider a custom middleware function defined as const myMiddleware = (req, res, next) => { /* ... */ };
Which of the following statements about its behavior is TRUE?
Custom Middleware Recap
You've learned how to create and use custom Express middleware!
- Custom middleware functions have the signature
(req, res, next). - Calling
next()is crucial to pass control to the next middleware or route handler. - Middleware can modify the
reqandresobjects, making data available downstream. - You can apply middleware globally with
app.use()or to specific routes. - They are powerful for adding reusable logic like logging, authentication, or request timing.
Mastering custom middleware is key to building modular and efficient Express applications.
คำถามที่พบบ่อย
บทเรียน “การพัฒนามิดเดิลแวร์ Express แบบกำหนดเอง” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การพัฒนามิดเดิลแวร์ Express แบบกำหนดเอง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Node.js Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การพัฒนามิดเดิลแวร์ Express แบบกำหนดเอง”
เขียนฟังก์ชันมิดเดิลแวร์ Express ของคุณเองเพื่อเพิ่มความสามารถและทำให้การประมวลผลคำขอคล่องตัวขึ้น คุณปฏิบัติ Node.js Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Node.js Backend Development Bootcamp หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Node.js Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การพัฒนามิดเดิลแวร์ Express แบบกำหนดเอง” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Node.js Backend Development Bootcamp นี้ได้ไหม
ได้ บทเรียน Node.js Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การพัฒนามิดเดิลแวร์ Express แบบกำหนดเอง
- กลยุทธ์การจัดการข้อผิดพลาดทั่วทั้งระบบ
- การตรวจสอบอินพุตด้วย Joi/Express-Validator
- มิดเดิลแวร์ยืนยันตัวตนด้วย JWT