Frontend State Management with Vue and Vuex : Building the News API Server with Express JS

Building the News API Server with Express JS

Next step, let us install the express framework and other dependencies for our fake API server. 

npx express-generator fnn-base-api

This will generate a barebones express application for us and install the needed dependencies. After this is installed, we add two more dependencies to enable us to build our fake API data. 

yarn add faker cors

Faker enables us to generate data for testing out our application. 

CORS is a node.js package for providing an Express middleware that can be used to enable CORS with various options.

To enable our application to serve CORS, we import cors and we add these lines to our generated applications app.js file. 

const cors = require("cors");

In order to pass the CORS middleware, we add it to the app.js file as shown below: 

In the routes folder, create a new file called news.js. This is where our FNN news API would be built.  When I originally built this application, I was making news of the newsapi. Since this is rate limited in other words you can make a limited number of requests per day, I built this small server to make it easier to follow along with this tutorial. 

What this piece of code does is to generate a randomly sized array and populate it with fake data using the faker.js library. 

const express = require("express");
const router = express.Router();
const faker = require("faker");

function generateFakeNews() {
  const numberOfItems = Math.floor(Math.random() * 40 + 10);

  return [...Array(numberOfItems)].map(() => ({
    title: faker.lorem.words(),
    description: faker.lorem.sentence(),
    url: faker.internet.url(),
    urlToImage: faker.image.image(),
    content: faker.lorem.paragraphs(),

router.get("/:category", function (req, res, next) {

module.exports = router;

After this, we import and use the API in our app.js file.

const newsRouter = require("./routes/news");
app.use("/api/news", newsRouter);

 If you have the Postman or some other JSON client, you can test out the API.  Calling the API returns a JSON response as follows. 


course logo
Frontend State Management with Vue and Vuex
Number of sections:
Content length:
Delivery formats:


F Yeboah
I am a Software / UI developer with interests in Search Intensive applications, Information Architectures(IA), UX/UI, FRP, and Reusable Frontend Components Design.... Show more