Practical week 12: Node.js and Express

1. Create back-end app

> npx express-generator --no-view --git myapp

> cd myapp

> npm install

> npm start

If everything is done correctly when visiting http://localhost:3000/ in your browser you should see "Welcome to Express" page

2. Create the data

  • In the root of the project let's create new directory data

  • Let's create a new file inside data folder and call it users.json, let's paste content of this URL inside that file.

  • Let's create a new file inside data folder and call it posts.json, let's paste content of this URL inside that file.

3. Create an endpoint to retrieve users list

  • in the file /routes/users.js let's replace the content with:


const express = require('express');

const router = express.Router();

const fs = require('fs');


/* GET users tasks listing. */

router.get('/', function (req, res, next) {


fs.readFile('./data/users.json', (err, data) => {

if (err) throw err;

let tasks = JSON.parse(data);

res.json(tasks);

});


});


module.exports = router;

4. Create an endpoint to retrieve posts

  • Let's create file /routes/posts.js let's replace the content with:

const express = require('express');

const router = express.Router();

const fs = require('fs');


/* GET posts listing. */

router.get('/', function (req, res, next) {

fs.readFile('./data/posts.json', (err, data) => {

if (err) throw err;

let posts = JSON.parse(data);

res.json(posts);

});

});


module.exports = router;

In the app.js file let's register our new route
Let's add this on line #8:

var postsRouter = require('./routes/posts');

And add this on line #20:


app.use('/posts', postsRouter);

Tasks

  • Create a new endpoint in users route where you will pass an id as a path parameter and you will retrieve user with that id from data/users.json file

  • Create new endpoint on back-end to insert new post

    • POST localhost:3000/posts

    • Request body should be:
      {

"text": "Some text for post"

"media": {

"type" : "image" or "video"

"url": "http://url.to/the/media/resource"

}

}

"media" can be optional. Other fields such as create time, author, number of likes and id needs to be set on backend side (You can hardcode them)