Quiz Entry - updated: 2026.06.20
How do you return JSON from an Express endpoint?
Set the application/json content type and send a stringified object — or just call res.json(), which does both.
router.get('/', function(req, res) {
res.type('application/json');
const response = {};
if ('firstName' in req.query && req.query.firstName !== '') {
response.message = 'Hello ' + req.query.firstName;
} else {
response.error = "Parameter 'firstName' not set or empty";
res.status(400);
}
res.send(JSON.stringify(response));
});
Request: GET /hello?firstName=Anna
Response: {"message":"Hello Anna"}
Shortcut: Express has res.json() which combines type setting and stringify:
res.json({ message: 'Hello Anna' });