What is the output when accessing `/api` in this Node and Express code?
4 phương ánCó giải thích
const express = require('express');
const app = express();
app.use('/api', (req, res, next) => {
console.log('Middleware');
next();
});
app.get('/api', (req, res) => res.send('API'));
app.listen(3000);Các phương án trả lời
Chọn một phương ánLời giảiChọn phương án để mở
Đáp án đúng: "Logs middleware then processes GET handler". Lần theo mã: request GET /api khớp app.use('/api') trước tiên vì nó được khai báo trước, hàm này chạy console.log('Middleware') in Middleware ra console của server rồi gọi next(); Express tìm tiếp và gặp app.get('/api'), handler gọi res.send('API') nên client nhận phản hồi API. Phương án được chọn mô tả đúng trình tự ghi log ở middleware rồi xử lý ở handler GET. Cần nói thẳng về "Middleware API": nó gộp dòng log ở server với nội dung phản hồi HTTP thành một đầu ra, chỉ đúng nếu hiểu output là cả hai nơi, còn trình duyệt thực tế chỉ nhận API. "Only the API response if middleware skipped" sai vì middleware không bị bỏ qua: đường dẫn khớp và nó gọi next() bình thường. "Combined output from both functions" sai vì chỉ handler GET gửi phản hồi, middleware không ghi gì vào response, nên client không nhận đầu ra gộp từ cả hai hàm.
Cùng chương 3
______ is a fast, unopinionated and minimalist web framework for Node.jsCó lời giảiCâu hỏiHow do you add middleware to an Express application?Có lời giảiCâu hỏiConsider the following code snippet using Express.js. Identify which routes handle GET and POST requests. app.get('/users', ...); app.post('/users', ...); app.listen(3000, ...) (Choose 2 answers)Có lời giảiCâu hỏiCả 38 câu của chủ đề38 câu