Analyze the following Express.js code snippet and determine what it does when accessed via a web browser.

4 phương ánCó giải thích
Đề bài
const express = require('express');
const app = express();

app.use((req, res, next) => {
  console.log(`${req.method} request for '${req.url}'`);
  next();
});

app.get('/', (req, res) => {
  res.send('Welcome to the homepage!');
});

app.get('/about', (req, res) => {
  res.send('About us');
});

app.use((req, res) => {
  res.status(404).send('Page not found');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Các phương án trả lời

Chọn một phương án
Lời giảiChọn phương án để mở
Đáp án đúng gồm ba ý: "It logs all incoming requests to the console.", "It returns 'Welcome to the homepage!' for GET requests to the root URL." và "It returns a 404 error for any undefined routes.". Lần theo mã: middleware đầu tiên khai báo bằng app.use không kèm đường dẫn nên chạy cho mọi request, in ra phương thức và URL (ví dụ GET request for '/about') rồi gọi next() để chuyển request xuống các route phía sau. Route app.get('/') gửi chuỗi Welcome to the homepage!, route app.get('/about') gửi About us. Middleware cuối cùng đặt sau mọi route, chỉ được chạy khi không route nào trả lời trước đó, nên nó đặt mã trạng thái 404 và gửi Page not found cho mọi đường dẫn chưa định nghĩa; app.listen mở máy chủ ở cổng 3000. Trình duyệt khi gõ địa chỉ sẽ gửi GET, nên cả ba hành vi trên đều quan sát được. "It only handles POST requests." sai vì mã chỉ đăng ký app.get, không có app.post nào; một request POST tới gốc vẫn được middleware đầu ghi log nhưng rồi rơi xuống middleware 404 vì không có route POST khớp.

Cùng chương 3

Xuất hiện trong 1 bộ đề