JSON Responses
Part of the Express Basics section of Coddy's Node.js journey. Lesson 6 of 23.
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
EasyPrograms, like a phone app, need Recipe Box's data in a form they can read. Add a JSON API next to the pages.
- In
server.js, add a route for/api/recipes. It sends the wholerecipesarray as JSON. - Add a route for
/api/recipes/:id. It finds the recipe the way/recipes/:iddoes, and sends the whole recipe object as JSON, not only its title. For recipe 2, that is the object with"id": 2,"title": "Pancakes","tags": ["breakfast", "sweet"]and its servings. - When no recipe has that id, respond with status 404. You can send the text
No such recipe, as the page does.
Try it: Press Run and send /api/recipes. You should see a list of four recipes, starting with Tomato Soup. Send /api/recipes/2: the Pancakes object. Send /api/recipes/99: status 404. In the Headers tab, /api/recipes has a Content-Type of application/json. Then send /about: its Content-Type is text/html, because res.send with a string sends a page.
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.
All lessons in Express Basics
Practice on your own: Express playground