Categories

Tuesday, December 24, 2024
#919814419350 therichposts@gmail.com
Angular 12Bootstrap 5Express JsNodejsPostgreSQL

Angular 12 Showing PostgreSQL Data Using NodeJS Express WEB API

Angular 12 Showing PostgreSQL Data Using NodeJS Express WEB API

Hello to all welcome back on my blog therichpost.com. Today in this blog post, I am going to tell you, Angular 12 Showing PostgreSQL Data Using NodeJS Express WEB API.

Guys with this post, we will do below things:

  1. Angular 12 with bootstrap 5 setup.
  2. Nodejs setup with express + nodemon.
  3. Cors installation in NodeJS to solve cors issue while using API in Angular 12.
Working Video
Angular 12 Showing PostgreSQL Data Using NodeJS Express WEB API
Angular 12 Showing PostgreSQL Data Using NodeJS Express WEB API
PostgreSQL Shell
PostgreSQL Shell
Nodejs WEB API
Nodejs WEB API

Guy’s Angular 12 came and if you are new in Angular 12 then please check the below links with other tutorials:

  1. Angular 12 Tutorials
  2. Bootstrap 5
  3. Nodejs
  4. PostgreSQL

Guy’s here is working code snippet and please follow it carefully to avoid the mistakes:

1. Firstly friends we need fresh angular 12 setup and for this we need to run below commands but if you already have angular 12 setup then you can avoid below commands. Secondly we should also have latest node version(14.17.0) installed on our system:

npm install -g @angular/cli 

ng new angulardemo //Create new Angular Project

cd angulardemo // Go inside the Angular Project Folder

2. Now guy’s, here we need to run below command into our project terminal to install bootstrap 5 module for styling and good looks into our angular application(optional):

npm install bootstrap

npm i @popperjs/core

3. Now guy’s, now we need to add below code into our angulardemo/angular.json file to add bootstrap style:

...
 "styles": [
             ...
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              
            ],
            "scripts": [
            ...
            "node_modules/bootstrap/dist/js/bootstrap.js",
          
            ],

4. Now guy’s, now we need to add below code into our angulardemo/src/app/app.module.ts file to call API module:

...
import { HttpClientModule } from '@angular/common/http';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ...
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

5. Now guys, now we need to add below code into our angulardemo/src/app/app.component.html file to get final output on browser:

<div class="container p-5">
 
  <table class="table table-hover table-bordered">
    <thead>
      <tr>
        <th scope="col">ID</th>
        <th scope="col">User Name</th>
        <th scope="col">Country</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let user of users">
        
        <td>{{user.id}}</td>
        <td>{{user.username}}</td>
        <td>{{user.country}}</td>
      </tr>
    
    </tbody>
  </table>
  
 
  </div>

6. Now guys, now we need to add below code into our angulardemo/src/app/app.component.ts file:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 ...
  users: any;
  constructor(public http: HttpClient) {

   //Rest API Calling
    this.http.get('http://localhost:5000/users').subscribe(data => {
      this.users = data;
      console.log(this.users);
    
    });
  }
}

Guy’s now we will do Nodejs setup and make WB API using express:

1. Guys first create empty folder name `nodebackend` inside your pc any drive and then please below commands to set node modules:

npm init  

npm i express 

npm i nodemon -D

npm i pg pg-hstore

npm i --save cors

2. Now guy’s inside your nodebackend/package.json file add below code:

{
  "name": "postgres",
  "version": "1.0.0",
  "description": "This is test project.",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "serve": "nodemon index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "pg": "^8.7.1",
    "pg-hstore": "^2.3.4",
    "sequelize": "^6.6.5"
  },
  "devDependencies": {
    "nodemon": "^2.0.12"
  }
}

3. Now guy’s create `index.js` file inside nodebackend folder and add below code inside it:

const express = require('express');

//solve cors issue
const cors = require("cors");

const app = express();

app.use(cors());
const port = 5000;
const Pool = require('pg').Pool;
  //Enter here your Postres database details
const pool = new Pool({
    user: 'postgres',
    host: 'localhost',
    database: 'dbname',
    password: 'root',
    dialect: 'postgres',
    port: 5432
});
  
  //Database connection and also please create postgres database first
pool.connect((err, client, release) => {
    if (err) {
        return console.error(
            'Error acquiring client', err.stack)
    }
    client.query('SELECT NOW()', (err, result) => {
        release()
        if (err) {
            return console.error(
                'Error executing query', err.stack)
        }
        console.log("Connected to Database !")
    })
})
  
app.get('/users', (req, res, next) => {
    console.log("TEST DATA :");
    pool.query('Select * from users')
        .then(testData => {
            console.log(testData);
            res.send(testData.rows);
        })
})

app.listen(port, () => {
  console.log(`Horror jassa app is running on port ${port}.`);
});

4. Now guy’s run below command to run NodeJS:

npm run serve

Guy’s in the end please run ng serve command to check the out on browser(localhost:4200) and if you will have any query then feel free to comment below.

Guy’s I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad because with your views, I will make my next posts more good and helpful.

Jassa

Thanks.

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

2 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.