Bir İstek Gövdesini Okuma
Coddy'nin Node.js Journey'sinin Express Temelleri bölümünün bir parçası. Ders 13 / 20.
POST isteği gövdesinde veri gönderir ve Express, siz istemediğiniz sürece gövdeyi okumaz.
app.use(express.json());
app.post('/api/loans', (req, res) => {
const { bookId, member } = req.body;
res.status(201).json({ bookId, member, due: '2026-11-08' });
});GET bir şey ister; POST oluşturulacak bir şey gönderir. express.json(), her JSON gövdesini req.body içine okuyan bir ara yazılımdır. Bu olmadan req.body değeri undefined olur. Bir şey oluşturan rota, oluşturduğu öğeyle birlikte 201 yanıtı verir.
Kaydetmeden önce gövdeyi kontrol edin. Eksik bir alan istemcinin hatasıdır; bu nedenle 400 yanıtı verin ve hiçbir şeyi kaydetmeyin.
Görev
KolayPOST /api/recipesile{ "title", "tags" }, yeni bir id ile tarif ekler ve bu tarifle birlikte201yanıtını verir.titleyoksa:{ "error": "A recipe needs a title" }ile400yanıtı verilir.
Bir gövdeyle POST gönderin, ardından GET /api/recipes isteği gönderin, sonra da title olmadan POST gönderin.
Kendin dene
import express from 'express';
import { randomUUID } from 'node:crypto';
import { recipes } from './data.js';
const app = express();
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
app.use((req, res, next) => {
res.set('X-Request-Id', randomUUID());
next();
});
app.use(express.static('public'));
const escapeHtml = (text) =>
text
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"');
app.get('/', (req, res) => {
const items = recipes.map((r) => `<li><a href="/recipes/${r.id}">${escapeHtml(r.title)}</a></li>`);
res.send(`<link rel="stylesheet" href="/style.css"><h1>Recipe Box</h1><ul>${items.join('')}</ul>`);
});
// type('text') düz metin gönderir, bu yüzden her başlık ayrı bir satırda görünür.
app.get('/recipes', (req, res) => {
const { tag } = req.query;
const list = tag ? recipes.filter((recipe) => recipe.tags.includes(tag)) : recipes;
res.type('text').send(list.map((recipe) => recipe.title).join('\n'));
});
app.get('/recipes/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).send('No such recipe');
return;
}
res.send(recipe.title);
});
app.get('/api/recipes', (req, res) => {
res.json(recipes);
});
app.get('/api/recipes/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).json({ error: 'No such recipe' });
return;
}
res.json(recipe);
});
app.get('/about', (req, res) => {
res.send('Recipe Box collects family recipes.');
});
app.get('/menu', (req, res) => {
res.redirect(301, '/recipes');
});
app.get('/menu/:id', (req, res) => {
res.redirect(301, `/recipes/${req.params.id}`);
});
app.listen(3000, () => {
console.log('Recipe Box is running on port 3000');
});
Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.
Express Temelleri bölümündeki tüm dersler
3Middleware
İlk Middleware'iniz