Session 12 – Node.js II
1. Backend (Node.js and Postgres)
1. Clone the following repository Repo.
2. Navigate to the project directory
3. Install dependencies
> npm install
4. Run the project
> node server Or > nodemon server
5. We also need to install Cross-Origin Resource Sharing (CORS) by writing in the terminal
> npm install cors
6. Remember to add your password and the name of your database to the database.js
.
Note: you need to create a database in Postgres, but the table will be created automatically within your database, when you run the App.
// database.js const Pool = require('pg').Pool; const pool = new Pool({ user: "postgres", password: "[add your password here]", database: "[add the name of your database here]", host: "localhost", port: "5432" }); module.exports = pool;
7. Inspect the server.js
file and see how the previous modules, express, and cors are imported and used in the server.js
file.
// server.js const express = require('express'); const pool = require('./database'); const cors = require('cors') const port = process.env.PORT || 3000; const app = express(); app.use(cors()); // The express.json() function is a built-in middleware function in Express. // It parses incoming requests with JSON payloads and is based on body-parser. app.use(express.json()); `````````````` // Handling HTTP requests code will go here `````````````` app.listen(port, () => { console.log("Server is listening to port " + port) });
Handling HTTP requests
We will define the operations for our simple app that can respond to (1) create a post request, (2) Fetch all posts request, (3) Fetch a post based on its id request, (4) Update a post based on its id request, and (5) Delete a post based on its id request.
Method | URI | Action |
POST | /api/posts | Create a new post |
GET | /api/posts | Fetch all posts |
GET | /api/posts/:id | Fetch a post based on its id |
PUT | /api/posts/:id | Update a post based on its id |
DELETE | /api/posts/:id | Delete a post based on its id |
Handling POST requests
Task 1. Uncomment the following code in the server.js
file to handle POST requests, i.e., add a new post to the database.
app.post('/api/posts/', async(req, res) => { try { console.log("a post request has arrived"); const post = req.body; const newpost = await pool.query( "INSERT INTO posttable(title, body, urllink) values ($1, $2, $3) RETURNING*", [post.title, post.body, post.urllink] // $1, $2, $3 are mapped to the first, second and third element of the passed array (post.title, post.body, post.urllink) // The RETURNING keyword in PostgreSQL allows returning a value from the insert or update statement. // using "*" after the RETURNING keyword in PostgreSQL, will return everything ); res.json(newpost); } catch (err) { console.error(err.message); } });
Test the POST request depending on Postman (or Thunder - VSCode) by adding a new post to the database.
Write a POST request to http://localhost:3000/posts/ Do not forget to define the body of the POST request in Postman (press on body -> chose raw, then JSON). Basically, the body of the request contains the information about the new post, as follows:
{ "title": "A title", "body": "A body ", "urllink": "A url link " }
Handling GET – all request
Task 2. Uncomment the following code in the server.js
file to handle GET requests, i.e., retrieve all posts from the database.
app.get('/api/posts', async(req, res) => { try { console.log("get posts request has arrived"); const posts = await pool.query( "SELECT * FROM posttable" ); res.json(posts.rows); } catch (err) { console.error(err.message); } });
We can test this script depending on Postman (or Thunder - VSCode) by retrieving all posts from the database. Write a GET request to http://localhost:3000/posts/, or you can just paste this URI into your browser.
Handling GET requests with route parameter
Task 3. Uncomment the following code in the server.js
file to handle GET requests with route parameters, i.e., retrieve a specific post from within the database.
app.get('/api/posts/:id', async(req, res) => { try { console.log("get a post with route parameter request has arrived"); // The req.params property is an object containing properties mapped to the named route "parameters". // For example, if you have the route /posts/:id, then the "id" property is available as req.params.id. const { id } = req.params; // assigning all route "parameters" to the id "object" const posts = await pool.query( // pool.query runs a single query on the database. //$1 is mapped to the first element of { id } (which is just the value of id). "SELECT * FROM posttable WHERE id = $1", [id] ); res.json(posts.rows[0]); // we already know that the row array contains a single element, and here we are trying to access it // The res.json() function sends a JSON response. // This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.stringify() method. } catch (err) { console.error(err.message); } });
Test this GET request depending on Postman by retrieving a specific post from the database based on the id you specify. Write a GET request to http://localhost:3000/posts/:id, do not forget to replace the ":id" with a valid post id.
Handling PUT requests
Task 4. Uncomment the following code in the server.js
file to handle PUT requests, i. e., update a post in the database.
app.put('/api/posts/:id', async(req, res) => { try { const { id } = req.params; const post = req.body; console.log("update request has arrived"); const updatepost = await pool.query( "UPDATE posttable SET (title, body, urllink) = ($2, $3, $4) WHERE id = $1", [id, post.title, post.body, post.urllink] ); res.json(updatepost); } catch (err) { console.error(err.message); } });
Test the PUT request depending on Postman by updating an already existing post in the database. Write a PUT request to http://localhost:3000/posts/:id Do not forget to define the body of the PUT request in Postman and also add a valid id of an existing post to be modified.
{ "title": "A new title", "body": "A new body ", "urllink": "A new url link " }
Handling DELETE requests
Task 5. Uncomment the following code in the server.js
file to handle DELETE requests, i. e., delete a post from the database.
//const post = req.body; // we do not need a body for a delete request console.log("delete a post request has arrived"); const deletepost = await pool.query( "DELETE FROM posttable WHERE id = $1", [id] ); res.json(deletepost); } catch (err) { console.error(err.message); } });
Test this DELETE request depending on Postman by deleting an already existing post in the database. Write a DELETE request to http://localhost:3000/posts/:id
2. Frontend (Vue.js)
1. Clone the following repository Repo.
2. Install dependencies
> npm install
3. Compiles and hot-reloads for development
> npm run serve
4. Run the backend app (Node.js), and run the front-end app (Vue.js), and test how they can work together.