expressjsHow can I use Express.js and PostgreSQL together to create a web application?
Express.js and PostgreSQL can be used together to create a web application.
Example code
const express = require('express')
const { Client } = require('pg')
const app = express()
const client = new Client({
user: 'postgres',
host: 'localhost',
database: 'my_database',
password: 'my_password',
port: 5432,
})
client.connect()
app.get('/', (req, res) => {
client.query('SELECT * FROM users', (err, result) => {
if (err) {
console.log(err.stack)
} else {
res.send(result.rows)
}
})
})
app.listen(3000, () => {
console.log('Server listening on port 3000')
})
Output example
Server listening on port 3000
This code creates an Express.js application which connects to a PostgreSQL database and sends a query to the users table. It then sends the result of the query to the client.
Code explanation
const express = require('express')
: This imports the Express.js module.const { Client } = require('pg')
: This imports the PostgreSQL Client module.const app = express()
: This creates an Express.js application.const client = new Client({...})
: This creates a new PostgreSQL Client instance with the given configuration.client.connect()
: This connects to the PostgreSQL database.app.get('/', (req, res) => {...})
: This creates a route handler for the root route which sends a query to the users table in the database and sends the result to the client.app.listen(3000, () => {...})
: This starts the Express.js application on port 3000.
Helpful links
More of Expressjs
- How do I set the time zone in Express.js?
- How can I use Express.js to generate a zip response?
- How do I use Yarn to add Express.js to my project?
- How do I find Express.js tutorials on YouTube?
- How can I use Node.js and Express together to create a web application?
- How can I use Express.js to yield results?
- How can I use an ExpressJS webhook to receive data from an external source?
- How can I use Express.js and Winston together to create a logging system?
- How do I use Express.js to handle x-www-form-urlencoded data?
- How can I use Express.js with TypeScript?
See more codes...