JSON Responses
Part of the Express Basics section of Coddy's Node.js journey. Lesson 6 of 20.
A program that calls your server needs data it can read, not a sentence.
app.get('/api/weather', (req, res) => {
res.json({ city: 'Oslo', temp: 4, rain: true });
});JSON is a text format for objects and arrays. res.json(value) turns the value into JSON and sets the Content-Type header to application/json; a header is a named line sent with the response, and this one says what kind of body follows. The client gets {"city":"Oslo","temp":4,"rain":true} and reads temp as a number.
res.send with a string sends text/html, which a program would have to pick apart. Routes for programs usually start with /api, so pages and data never share a path.
Challenge
EasyGET /api/recipesanswers therecipesarray as JSON.GET /api/recipes/:idanswers one recipe as JSON; an unknown id answers404.
Send GET /api/recipes, GET /api/recipes/2 and GET /api/recipes/99. Compare the headers with GET /recipes.
Try it yourself
import express from 'express';
import { recipes } from './data.js';
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to Recipe Box');
});
// type('text') sends plain text, so each title shows on its own line.
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');
});
This lesson includes a short quiz. Start the lesson to answer it and track your progress.