What is the response when a GET request is made to `http://localhost:3000/profile` in the following Express application? Assume the request includes `?token=xyz`.

4 phương ánCó giải thích
Đề bài
const express = require('express');
const app = express();
const logger = (req, res, next) => {
  req.log = `${req.method} ${req.url}`;
  next();
};
const restrict = (req, res, next) => {
  if (!req.query.token) {
    res.status(403).send('Forbidden');
  } else {
    next();
  }
};
app.use(logger);
app.get('/profile', restrict, (req, res) => {
  res.json({ log: req.log, user: 'Alice' });
});
app.listen(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: "{ log: 'GET /profile', user: 'Alice' }". Lần theo mã: app.use(logger) chạy với mọi yêu cầu, gán req.log bằng method nối với url rồi gọi next(); route GET /profile có middleware restrict đứng trước handler, vì yêu cầu kèm ?token=xyz nên req.query.token là xyz, khác rỗng, restrict gọi next(); handler cuối trả res.json với log lấy từ req.log và user là Alice. Cần nói thẳng một chi tiết: req.url ở middleware gắn tại gốc vẫn giữ chuỗi truy vấn, nên giá trị log thực tế là GET /profile?token=xyz; dù vậy phương án này đúng cấu trúc phản hồi và đúng luồng chạy, nên vẫn là lựa chọn đúng. "403 status with 'Forbidden'" chỉ xảy ra khi thiếu token. "{ user: 'Alice' }" sai vì handler có đưa trường log vào JSON. "Throws an error due to undefined `req.log`" sai vì logger chạy trước và đã gán req.log.

Cùng chương 8

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