Using Node to connect to PostgreSQL database and make a POST request. The database itself is connected (tested with some simple GET requests). But it seems that for some reason the client is not defined when running my registration function.
Here’s my code for connecting to the database;
import pg from "pg";
const client = new pg.Client({
host: 'localhost',
user: 'stephen',
port: 5433,
database: "ecommerceapp"
});
client.connect();
client.query(`SELECT * FROM customer`, (err, res) => {
if(!err) {
console.log(res.rows);
} else {
console.log(err.message);
}
client.end;
});
And here’s my user registration function
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const { client } = import("../db/index.mjs");
exports.register = async (req, res) => {
const { name, email, password} = req.body;
try {
const data = await client.query(`SELECT * FROM customer WHERE email=$1`, [email]);
const arr = data.rows;
if(arr.length != 0) {
return res.status(400).json({
error: "Email already in use.",
});
}
else {
bcrypt.hash(password, 10, (err, hash) => {
if(err)
return res.status(err).json({
error: "Server error",
});
const user = {
name,
email,
password: hash
};
var flag = 1;
client.query(`INSERT INTO customer (name, email, password) VALUES ($1, $2, $3);`, [user.name, user.email, user.password], (err) => {
if(err) {
flag = 0;
console.error(err);
return res.status(500).json({
error: "Database error",
})
} else {
flag = 1;
res.status(200).send({message: 'User added to databse, not verified'});
}
})
if(flag) {
const token = jwt.sign({
email: user.email
},
process.env.SECRET_KEY
);
}
})
}
}
catch(err) {
console.log(err);
return res.status(500).json({
error: "Database error while registering user",
});
};
}
I have tried variations of requiring/importing the {client} variable into my registration code, but I’m worried that some kind of unseen error in the code is being thrown and as a result, client is undefined.
2
Answers
Your script doesn’t compile… and there’s lots of missing semicolons (some critical).
https://closure-compiler.appspot.com/home
I don’t know if what you’ve posted here is exactly what you’re using but we can only go by what’s posted here.
Due to asynchronous nature of Javascript, the code inside callback function of
bcrypt.hash
will execute after register method is complete, in which case the variable "client" will be out of scope.Try wrapping the
bcrypt.hash
function in a promise as outlined here and await the call to finish before invokingclient.query('INSERT INTO customer ....')
. Use await syntax for the query call as well, similar toconst data = await client.query('SELECT ... ')
call