Exposing Data
Let's cover how to expose data through custom API.
Here, we’ll publish some blog articles. The API route is "/api/articles"
, and the associated callback returns a list of JavaScript objects. Here’s the code to be added to the server just before the last part (the one that starts the listening).
// Define an article list
const articles = [
{ id: 1, title: "First article", content: "Hello World!" },
{
id: 2,
title: "Lorem ipsum",
content:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut hendrerit mauris ac porttitor accumsan. Nunc vitae pulvinar odio, auctor interdum dolor. Aenean sodales dui quis metus iaculis, hendrerit vulputate lorem vestibulum."
},
{
id: 3,
title: "Lorem ipsum in French",
content:
"J’en dis autant de ceux qui, par mollesse d’esprit, c’est-à -dire par la crainte de la peine et de la douleur, manquent aux devoirs de la vie. Et il est très facile de rendre raison de ce que j’avance."
}
];
// Return the articles list in JSON format
app.get("/api/articles", (request, response) => {
response.json(articles);
});
Get hands-on with 1400+ tech skills courses.