JSON 응답
Coddy Node.js 여정의 Express 기초 섹션에 포함된 레슨. 20개 중 6번째.
서버를 호출하는 프로그램에는 문장이 아니라 읽을 수 있는 데이터가 필요합니다.
app.get('/api/weather', (req, res) => {
res.json({ city: 'Oslo', temp: 4, rain: true });
});JSON은 객체와 배열을 위한 텍스트 형식입니다. res.json(value)은 값을 JSON으로 변환하고 Content-Type 헤더를 application/json으로 설정합니다. 헤더는 응답과 함께 전송되는 이름이 붙은 줄이며, 이 헤더는 뒤에 어떤 종류의 본문이 오는지 알려 줍니다. 클라이언트는 {"city":"Oslo","temp":4,"rain":true}를 받고 temp를 숫자로 읽습니다.
문자열과 함께 사용하는 res.send는 text/html을 보내므로, 프로그램은 이를 분해해서 읽어야 합니다. 프로그램용 경로는 보통 /api로 시작하므로 페이지와 데이터가 같은 경로를 공유하지 않습니다.
챌린지
쉬움GET /api/recipes는recipes배열을 JSON으로 응답합니다.GET /api/recipes/:id는 레시피 하나를 JSON으로 응답하며, 알 수 없는 id에는404로 응답합니다.
GET /api/recipes, GET /api/recipes/2, GET /api/recipes/99를 전송하세요. 헤더를 GET /recipes와 비교하세요.
직접 해보기
import express from 'express';
import { recipes } from './data.js';
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to Recipe Box');
});
// type('text')는 일반 텍스트를 전송하므로 각 제목이 한 줄씩 표시됩니다.
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('/about', (req, res) => {
res.send('Recipe Box collects family recipes.');
});
app.listen(3000, () => {
console.log('Recipe Box is running on port 3000');
});
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.