StudyCode
Узнаём смысл кодов ответа и возвращаем правильный статус в каждой ситуации.
HTTP-статусы делятся на группы:
2xx — Успех: 200 OK · 201 Created · 204 No Content
3xx — Редирект: 301 Moved · 302 Found
4xx — Ошибка клиента: 400 Bad Request · 401 Unauthorized · 403 Forbidden · 404 Not Found
5xx — Ошибка сервера: 500 Internal Server Error
В Express: res.status(404).json({ error: '...' })
// Примеры правильного использования:
app.post('/users', (req, res) => {
if (!req.body.name) {
return res.status(400).json({ error: 'name is required' }); // Bad Request
}
const user = createUser(req.body);
res.status(201).json(user); // Created
});
app.get('/users/:id', (req, res) => {
const user = findUser(req.params.id);
if (!user) return res.status(404).json({ error: 'Not found' }); // Not Found
res.json(user); // 200 OK по умолчанию
});res.status(201).json({ id: 7, name: "Аня" })if (!name) {
return res.status(400).json({
error: "Validation failed",
message: "name is required"
});
}Пустое имя — вина клиента, значит 4xx, а не 500.