Câu hỏi: SDN302 Server-Side development with NodeJS, Express, and MongoDB – Bộ ôn tập cuối kỳ số 3
50 câu trắc nghiệm kèm lời giải của môn Server-Side development with NodeJS, Express, and MongoDB, xếp đúng thứ tự trong đề. Trang 2/3 — câu 21–40.
Danh sách câu hỏi
const express = require('express');
// Example from generated routeĐáp án đúng: "Router files like index.js and users.js". Express Generator (lệnh npx express-generator) dựng khung dự án gồm app.js, bin/www và các thư mục public, views, routes; trong routes có hai tệp index.js và users.js, mỗi tệp gọi express.Router(), khai báo route rồi xuất router ra để app.js gắn bằng app.use('/', indexRouter) và app.use('/users', usersRouter). "Template files for views and layouts" nằm ở thư mục views (như index.jade, layout.jade, hoặc tệp .ejs khi chọn engine EJS), không ở routes. "Model definitions for database interactions" sai vì Express Generator không sinh tầng model hay kết nối cơ sở dữ liệu nào, lập trình viên tự thêm. "Asset folders for static content serving" nằm ở thư mục public (images, javascripts, stylesheets), được phục vụ qua express.static.
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);Đáp án đúng: "They allow for reusable template pieces". Partial trong Handlebars là một mẩu template được đăng ký một lần bằng Handlebars.registerPartial (hoặc đặt trong thư mục partials khi dùng express-handlebars hay hbs) rồi chèn vào nhiều trang bằng cú pháp {{> header}}, rất hợp cho đầu trang, chân trang, menu dùng chung: sửa một chỗ là mọi trang đổi theo. "They define conditional logic in templates" là việc của helper khối như {{#
if
}
}và {{#each}}, không phải partial. "They manage server-side routing" là việc của Express với app.get hay Router; Handlebars chỉ sinh HTML từ dữ liệu. "They compile templates into JavaScript" mô tả hàm Handlebars.compile, áp dụng cho mọi template chứ không phải vai trò riêng của partial.
SQLNoSQLRelationalHierarchicalasync function fetchData() {
try {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();What are the advantages of using async/await in this code?
Đáp án đúng gồm hai ý: "Import the MongoClient class from the mongodb module with the require() statement." và "Call the connect() method on the MongoClient instance by passing the MongoDB server URL.". Với driver mongodb chính thức theo kiểu CommonJS, đầu tiên lấy lớp bằng const { MongoClient } = require('mongodb'), sau đó tạo client và gọi connect() với chuỗi kết nối như mongodb://localhost:27017 (bản driver mới thường truyền URL vào new MongoClient(url) rồi gọi client.connect(), bản cũ dùng MongoClient.connect(url)); kết nối xong mới gọi client.db() để chọn database. "Create an instance of the MongoDatabase class." sai vì driver không có lớp MongoDatabase; đối tượng database có kiểu Db và lấy qua client.db(), không tự tạo bằng new. "Use the import statement to import MongoClient." chỉ đúng khi dự án dùng ES module, còn quy trình được hỏi dựa trên require() của CommonJS nên đây không phải bước bắt buộc.
mongoose.createSchema()mongoose.newSchema()mongoose.Schemamongoose.modelconst express = require('express');
const mongoose = require('mongoose');
const app = express();mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
const userSchema = new mongoose.Schema({ name: String });
const User = mongoose.model('User', userSchema);
app.get('/api/users/search', async (req, res) => {
const { name } = req.query;
const users = await User.find({ name: new RegExp(name, 'i') });
res.json(users);
});
app.listen(3000);Assume the database has users: { name: "Alice" }, { name: "Bob" }, { name: "Alan" }.
Model.find()Model.insert()Model.save()new Model().save()