Setting up a Node.js App for an MVC project
To Set up a Node.js project, and install nodemon and Express, please refer to the material from the previous week. Therefore, we assume that your project is already there, and the information here will focus on Setting up a Node.js App for an MVC project.
Connecting our server to Postgres:
1. We need to install node-postgres (pg) by writing in the terminal
> npm install pg
2. We also need to install Cross-Origin Resource Sharing (CORS) to avoid cross-origin errors.
CORS is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.
CORS allows us to relax the security applied to an API. This is done by bypassing the Access-Control-Allow-Origin headers, which specify which origins can access the API. For example, if the client and the server have the same origin (e.g., http://localhost:3000/), accessing resources will be successful. However, if they have different origins from one another (The back end is running on http://localhost:3000/, and the front end is running on http://localhost:8080/, accessing resources will be prevented. That is why we need to use CORS to overcome this problem.
We can install cors by writing in the terminal
> npm install cors
3. We need to connect our server to our database, to do that create a file and name it database.js
. Then, paste the following script into it. Remember to add your password and the name of your database.
// 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;
4. Import/include the previous modules, express, and cors into your main js file (server.js). Then, create the cors() and express.json() middlewares after the app instance. Finally, Make your server listen to port 3000. Now, the code should look as follows:
// 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) });