我是NodeJS和Express的新手,我按照一个教程创建了一个与Mysql的连接的CRUD,其中使用了“ express-myconnection”,该连接被记录为中间件,并从模型或控制器中使用。但是我需要使用postgresql,我设法建立了连接,我的问题是我无法从模型或控制器中调用它
const express = require('express');
const path = require('path');
const morgan = require('morgan');
const app = express();
const { Client } = require('pg');
const connectionData = {
user: 'postgres',
host: 'localhost',
database: 'bex',
password: 'postgres',
port: 5432,
}
const client = new Client(connectionData);
client.connect()
client.query('SELECT * FROM bex_usuario')
.then(response => {
console.log(response.rows)
client.end()
})
.catch(err => {
client.end()
})
您将如何创建类似于“ express-myconnection”的中间件,或者如何在不需要在每个模型或控制器中定义它的情况下从我的模型或控制器实例化?
答案 0 :(得分:0)
const { Pool } = require('pg');
function connectionMiddleware(connectionData) {
const pool = new Pool(connectionData);
return (req, res, next) => {
req.pool = pool;
next();
}
}
app.use(connectionMiddleware({
user: 'postgres',
host: 'localhost',
database: 'bex',
password: 'postgres',
port: 5432,
}));
app.use((req, res, next) => {
req.pool.connect((err, client, release) => {
client.query('SELECT NOW()', (err, result) => {
release();
if (err) return next(err);
console.log(result.rows);
res.send(200);
});
});
});