I have created an app on heroku server and installed Postgres free add-on. Now I have a nodejs project in which I am connecting this database using pg modules. So for this I have created
db-connect.js
var { Pool } = require('pg');
var nodeEnvFile = require("node-env-file");
nodeEnvFile(".env");
var config = {
user: process.env.DB_USER,
host: process.env.DB_IP,
database: process.env.DB,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
max: 10, // max number of connection can be open to database
idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed
};
var pool = new Pool(config);
module.exports = {
query: (query, callback) => {
console.log(query);
pool.connect().then(client => {
return client.query()
.then((result) => {
client.release();
console.log(result.rows)
callback(null, result.rows[0]);
})
.catch(err => {
client.release();
callback(err, null);
});
})
}
}
and then in the API layer, I have imported this file
const db = require("../db/db-connect");
and used like this
router.get("/getdata/", (req, res) => {
var query = "query";
db.query(query, (err, result) => {
if (err) {
res.status(400).send(err);
}
res.send(result);
})
});
and this was showing following error
(node:1984) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): error: no pg_hba.conf entry for host "157.39.161.5", user "ltolmhjmwnfokl", database "den55ln368anf8", SSL off
(node:1984) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
select * from get_notifications('sidhu',0,1);
(node:1984) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): error: no pg_hba.conf entry for host "157.39.161.5", user "ltolmhjmwnfokl", database "den55ln368anf8", SSL off
and then I enabled ssl option in the config object
var config = {
user: process.env.DB_USER,
host: process.env.DB_IP,
database: process.env.DB,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
max: 10, // max number of connection can be open to database
idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed
ssl: true
};
but now this is showing
(node:252) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'submit' of undefined
(node:252) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
ServiceUnavailableError: Response timeout
at IncomingMessage.<anonymous> (D:\PROJECTS\PuWifi\GitHubForHeroKu\PuWifi\node_modules\connect-timeout\index.js:84:8)
at emitOne (events.js:116:13)
at IncomingMessage.emit (events.js:211:7)
at Timeout._onTimeout (D:\PROJECTS\PuWifi\GitHubForHeroKu\PuWifi\node_modules\connect-timeout\index.js:49:11)
at ontimeout (timers.js:475:11)
at tryOnTimeout (timers.js:310:5)
at Timer.listOnTimeout (timers.js:270:5)
what is the issue? Am I missing something?
Actually, I was missing to pass the query in client.query(). It should be client.query(query). Here is the code
module.exports = {
query: (query, callback) => {
console.log(query);
pool.connect().then(client => {
return client.query()
.then((result) => {
client.release();
console.log(result.rows)
callback(null, result.rows[0]);
})
.catch(err => {
client.release();
callback(err, null);
});
})
}
}
The other is to use pool.query
module.exports = {
query: (query, callback) => {
console.log(query);
pool.query(query).then(response => {
callback(null, response.rows);
}).catch(err => {
callback(err, null);
})
}
}
For detail: https://github.com/brianc/node-postgres/issues/1597#issuecomment-375554709
Related
I'm setting up a login system with nano, passport and couchdb. Things are mostly working but when couchdb is offline I'm given this error:
(node:893) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:5984
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
(node:893) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:893) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
My code:
const LocalStrategy = require('passport-local').Strategy;
const nano = require('nano')('http://admin:password#localhost:5984');
const users = nano.use('users');
const bcrypt = require('bcrypt');
module.exports = function(passport) {
passport.use(new LocalStrategy(
function(username, password, done) {
users.view('auth', 'auth', {'key': username, 'include_docs': true})
.then(dbresponse => {
if (dbresponse.rows.length === 1) {
const user = dbresponse.rows[0].doc;
bcrypt.compare(password, user.password, function(err, result) {
if(result === true) {
done(null, user)
} else {
done(null, false)
}
});
} else {
done(null, false);
}
})
}
));
};
I can't have the entire app stop working when the database is offline. I'd like to handle this error somehow but I can't figure out how.
I am trying to implement my first user login authentication with jwt. I have a registration endpoint, where I have populated fake data. Now I want to login with the data I have in database. I am testing via Postman, but I have an error which is
[Object: null prototype] {
email: 'fakeEmail#gmail.com\t',
password: '12345678'
}
(node:14781) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'password' of undefined
at /home/me/coding/project/backend/routes/user.js:38:40
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:14781) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:14781) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
POST /user/login - - ms - -
Assuming it might be because of bodyparser, i have tried both way
//app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser());
but same error.
Here is my login endpoint
router.post("/login",(req, res) => {
const {email, password } = req.body;
console.log(req.body)
pool
.query("SELECT * FROM users WHERE email = $1 AND password = $2 LIMIT 1", [email, password ])
.then(res => {
const data = res.rows[0];
if ( email && password === data.password) {
const token = jwt.sign({ email: req.body.email }, "mySecretKey", {
expiresIn: "30 day",
});
res.send(token);
} else {
res.sendStatus(401);
}
});
});```
You have a problem in res object try loging res in then block. res.rows[0] seems undefined
My problem was, that I have registration endpoint, where I am using Bcrypt, and I had to Verify in Login endpoint. Therefore I was getting errors.
So, here is my corrected Login endpoint
router.post("/login", (req, res) => {
const { email, password } = req.body;
pool
.query("SELECT * FROM users WHERE email = $1 LIMIT 1", [email])
.then((result) => {
const data = result.rows[0];
if (result.rows.length > 0 && email) {
bcrypt.compare(password, data.password, function (err, result) {
if (result) {
const token = jwt.sign({ email: req.body.email }, "mySecretKey", {
expiresIn: "30 days",
});
res.send(token);
} else {
res.sendStatus(401);
}
});
} else {
res.sendStatus(401);
}
});
});
I hope, it will help someone having similar issue
I'm trying to fix an error UnhandledPromiseRejectionWarning: Error: querySrv ECONNREFUSED when I make an axios call to fetch user data from mongoose query without internet connection. I've tried to wrap both the mongoose query User.findOne() and mongoose.connect() with try catch, but the error still remain.
(node:3966) UnhandledPromiseRejectionWarning: Error: querySrv
ECONNREFUSED _mongodb._tcp.cluster1-94jth.mongodb.net [0] at
QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19) [0] (node:3966)
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not handled
with .catch(). (rejection id: 1) [0] (node:3966) [DEP0018]
DeprecationWarning: Unhandled promise rejections are deprecated. In
the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.
FRONT-END
client.js
try {
const res = await axios.get('/auth/user?', {
params: {
refreshToken: refreshToken,
userID: userID
}
}
);
console.log(res.data);
} catch (error) {
if(error.toJSON().message === 'Network Error'){
alert('no internet connection');
}
}
BACK-END
auth.routes.js
auth.get(
'/user',
async(req, res)=>{
try {
const {userID, refreshToken, uniqueDeviceID, authTimestamp} = req.query;
const existingUser = await User.findOne({
$and: [
{'user_id': userID},
{'refresh_token': refreshToken}
]
});
res.send(existingUser);
} catch (error) {
console.log(error);
}
}
);
server.js
try {
mongoose.connect(keys.mongoURI, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true});
console.log('Database Connected');
} catch (error) {
console.log(error);
}
Wrapping mongoose.connect with try/catch will not work because its no doing async/await.
You should:
mongoose.connect(keys.mongoURI, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true})
.then(() => console.log('Database Connected'))
.catch(error=> console.log(error));
try/catch won't work with an asynchronous function without await
so to catch an error from asynchronous function:
try {
await someAsyncFunction();
} catch (e) {
//...
}
or you could use catch method from Promise or even use callbacks.
I'm creating an endpoint for a user to login. it looks to see if a user has a refresh cookie and if not, generates a pair of auth and refresh tokens.
async login(_, { email }, { req, res }) {
try {
const user = await User.findOne({ where: { email } });
if (!user) {
throw new Error("*** COULDN'T FIND USER WITH EMAIL ", email);
}
const tokenAuth =
jsonwebtoken.sign({ id: user.id, email: user.email }, SECRET_AUTH, { expiresIn: TOKEN_AUTH_EXPIRY });
const tokenRefresh =
jsonwebtoken.sign({ id: user.id, email: user.email }, SECRET_REFRESH, { expiresIn: TOKEN_REFRESH_EXPIRY });
const saveRefreshToken = await Token.create({
hash: tokenRefresh,
user_id: user.id,
})
const tokens = {
tokenAuth,
tokenRefresh
}
res.cookie('tokenAuth', tokenAuth, { httpOnly: true, maxAge: 300000 })
res.cookie('tokenRefresh', tokenRefresh, { httpOnly: true, maxAge: 2592000000 })
res.status(200).send({ data: { message: "Tokens Generated!", tokens, login: true }});
} catch(e) {
console.log('*** Error on /login:', e)
}
}
But I get the following errors
(node:14905) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at apollo_server_core_1.runHttpQuery.then (/Users/z/server/node_modules/apollo-server-express/src/expressApollo.ts:42:17)
(node:14905) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:14905) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I'm only sending back one res, so why's it throwing that error?
I'm sending an email through nodemailer, I'm using sequelize transaction to rollback the above task if email not sent, I'm getting the error while rejecting Promise or throwing an error.
Please help.
//Transaction
await db.sequelize.transaction(async t => {
const facility = await db.Facility.create(body, {transaction: t});
const user = await userCmp.addUser(email.email, t); // add user
await facilityUserCmp.addFacilityUser(facility.id, user.id, t); // add facility_user
emailCmp.verification(user, t); // notify user
if (user) {
res.status(201).send({
success: true,
errors: [],
data: facility
});
}
});
emailCmp.verification(user, t); // this is the function to send an email.
sending Email code.
verification: (user, t) => {
try {
const smtpTransport = nodemailer.createTransport({
service: 'SendGrid',
auth: {
user: 'wrong username',
pass: 'wrong password'
}
});
const mailOptions = {
to: 'test email',
from: 'test email',
subject: 'test subject',
text: 'Testing email'
};
smtpTransport.sendMail(mailOptions)
.then((success) => {
console.log(success);
}).catch((e) => {
throw new Error(e);
});
} catch (e) {
console.log("inside catch -p---------------");
}
Exception :
(node:10492) UnhandledPromiseRejectionWarning: Error: Invalid login: 535 Authentication failed: Bad username / password
at SMTPConnection._formatError (C:\Users\******\*****\node_modules\nodemailer\lib\smtp-connection\index.js:606:19)
at SMTPConnection._actionAUTHComplete (C:\Users\******\*****\node_modules\nodemailer\lib\smtp-connection\index.js:1335:34)
at SMTPConnection._responseActions.push.str (C:\Users\******\*****\node_modules\nodemailer\lib\smtp-connection\index.js:366:26)
at SMTPConnection._processResponse (C:\Users\******\*****\node_modules\nodemailer\lib\smtp-connection\index.js:762:20)
at SMTPConnection._onData (C:\Users\******\*****\node_modules\nodemailer\lib\smtp-connection\index.js:558:14)
at TLSSocket._socket.on.chunk (C:\Users\******\*****\node_modules\nodemailer\lib\smtp-connection\index.js:709:51)
at TLSSocket.emit (events.js:182:13)
at addChunk (_stream_readable.js:283:12)
at readableAddChunk (_stream_readable.js:264:11)
at TLSSocket.Readable.push (_stream_readable.js:219:10)
at TLSWrap.onread (net.js:638:20)
(node:10492) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:10492) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Please help me out.