2024-11-22 web, development, javascript
Express App with PostgreSQL Integration
By O. Wolfson
Create a simple Node.js application using Express and integrate it with a PostgreSQL database using the pg
library. Our application will provide APIs to fetch and add customer data in a PostgreSQL database.
Prerequisites
- Node.js installed on your machine.
- PostgreSQL server accessible either locally or remotely.
- Basic understanding of JavaScript and Node.js.
Step 1: Setting Up Your Project
-
Initialize a New Node.js Project: Create a new directory for your project and initialize a new Node.js project by running:
-
Install Dependencies: Install Express and
pg
(PostgreSQL client for Node.js) by running:
Step 2: Writing Your Express Application
-
Create an
app.js
File: This file will contain our application code. Start by requiring necessary modules and setting up the Express app. -
Configure PostgreSQL Connection: Use the
pg
library to connect to your PostgreSQL database. Ensure you use environment variables for sensitive data like passwords. -
Set Up Express JSON Middleware: To handle JSON payload in requests, use
express.json()
. -
Create an API to Fetch Data: Define a GET endpoint to fetch all customers from your database.
-
Create an API to Add a Client: Define a POST endpoint to add new customer data to your database.
-
Start Your Express Server: Finally, listen on the specified port.
Step 3: Running Your Application
-
Set Your Database Password: Before running your application, make sure to set the
PG_PASSWORD
environment variable to your PostgreSQL user's password. This can be done in your terminal or within a.env
file if you're using a package likedotenv
. -
Start Your Application: Run your application using Node.js.
-
Testing Your APIs: You can test your APIs using tools like Postman or
curl
commands. For example, to fetch customer data:
To add a new client: