Connessione a PostgreSQL con Node.js

Mattepuffo's logo
Connessione a PostgreSQL con Node.js

Connessione a PostgreSQL con Node.js

Continuando l'esplorazione di PostgreSQL, oggi vediamo come connetterci con Node.js.

Useremo due moduli:

  • expressjs
  • pg

Quindi nel nostro package.json:

{
    "name": "PostgreSQL",
    "version": "1.0.0",
    "keywords": [
        "util",
        "functional",
        "server",
        "client",
        "browser"
    ],
    "author": "matte",
    "contributors": [],
    "dependencies": {
        "express": "*",
        "pg": "*"
    }
}

E date questo comando:

$ npm install

Create un file Javascript come entrypoint con questo dentro:

// main.js
var express = require('express');
var app = express();
var port = 8080;
const pg = require('pg');
const config = {
    user: 'postgres',
    database: 'test',
    password: 'postgres',
    port: 5432,
    host: '192.168.1.31'
};
const pool = new pg.Pool(config);

app.get('/', function (req, res, next) {
    pool.connect(function (err, client, done) {
        if (err) {
            done();
            console.log(err);
            return res.status(500).json({success: false, data: err});
        }

        client.query('SELECT * FROM tbl_test', function (err, result) {
            done();
            if (err) {
                console.log(err);
                res.status(400).send(err);
            }
            res.status(200).send(result.rows);
        })
    });
});

app.listen(port, function () {
    console.log('Express server inizializzato sulla porta ' + port);
});

Provate ad avviare il programma ed andare con il browser sull'indirizzo:

$ node main.js

Dovreste vedere l'output in formato JSON sul browser.

Enjoy!


Condividi

Commentami!