no PostgreSQL user name specified in startup packet - database

^
no PostgreSQL user name specified in startup packet```
const { Pool } = require('pg');
const pool = new Pool({
connectionString: process.env.DATABASE_URL
});
console.log('ok connected')
pool.query('SELECT * FROM todo', (error, result) => {
if (error) {
throw error.message;
}
console.log(result.rows);
});
process.on('SIGINT', () => {
pool.end();
});
Iam using postgresql with express js , trying to connect to database but its show this error
i am using ElephantSQL service for this project

Related

How to connect HiveMqtt to React app using mqtt package

I am trying to connect my react application to HiveMQ using mqtt.js package but I am having this error.
This is the code I used
useEffect(() => {
const options: IClientOptions = {
protocol: "ws",
username: "myfirstdevice",
password: "qweqwe123",
};
const client = mqtt.connect('ws://8dedd20fc1164c8e9ce132a8a8359991.s1.eu.hivemq.cloud:8884', options);
// const client = mqtt.connect(options);
client.on('connect', function () {
console.log('Connected');
});
client.on('error', function (error) {
console.log("ERROR", error);
});
client.on('message', (topic,message,packet)=>{
console.log("RECEIVE", topic)
console.log("RECEIVE", message)
console.log("RECEIVE", packet)
});
}, []);
Port 8884 is for MQTT over Secure WebSockets
You'll need to change the URL to start with wss:// not ws://

aws-sdk Cannot read properties of undefined (reading 'region') in react

I'm importing the following in my react app
const AWS = require('aws-sdk/dist/aws-sdk');
upon onSuccess in authenticateUser i'm getting the following error
onSignInFailure: TypeError: Cannot read properties of undefined (reading 'update')
at Object.onSuccess (authenticate.ts?c0c4:55:1)
at CognitoUser.authenticateUserInternal (CognitoUser.js?3c43:470:1)
at eval (CognitoUser.js?3c43:333:1)
at eval (CognitoUser.js?3c43:312:1)
at eval (Client.js?1610:140:1)
My code
import { CognitoUser, AuthenticationDetails } from "amazon-cognito-identity-js";
import Pool from "./UserPool";
const AWS = require('aws-sdk/dist/aws-sdk');
const authenticate = async (Username, Password) => (
await new Promise((resolve, reject) => {
const user = new CognitoUser({ Username, Pool });
const authDetails = new AuthenticationDetails({ Username, Password });
user.authenticateUser(authDetails, {
onSuccess: data => {
console.log('onSuccess:', data);
// AWS.config.region = 'us-east-1';
AWS.config.update({region: 'us-east-1'});
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', // your identity pool id here
Logins: {
// Change the key below according to the specific region your user pool is in.
'cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxxxxxx': data
.getIdToken()
.getJwtToken(),
},
});
console.log(AWS.config.credentials);
//refreshes credentials using AWS.CognitoIdentity.getCredentialsForIdentity()
AWS.config.credentials.refresh(error => {
if (error) {
console.error('refresh err: ',error);
} else {
// Instantiate aws sdk service objects now that the credentials have been updated.
// example: var s3 = new AWS.S3();
console.log('Successfully logged!');
}
});
resolve(data);
},
onFailure: err => {
console.error('onSignInFailure:', err);
reject(err);
}
});
})
)

Invalid Credentials Error when tried to access a public data from a dynamo db table

I am using an aws-sdk in create-react-app to fetch dynamo DB data as a Guest user. In the Identity Pool, I have an unauthorized role that has limited access to a few tables that is public. When I tried to access data with the code below it shows Invalid credentials. I am new to aws, dynamo DB, I went through the documentation and tried out things. It's not worked as it is a bit different case.Please guide me the right approach to do this.
useEffect(() => {
AWS.config.update({
region: process.env.REACT_APP_REGION,
credentials: new AWS.CognitoIdentityCredentials({
IdentityPoolId: process.env.REACT_APP_USER_POOL_ID
})
});
const docClient = new AWS.DynamoDB.DocumentClient();
const params = {
TableName: "test_data",
Key:{ "id":"Test_2020_11_6_18"},
};
docClient.get(params, function(err, data) {
if (err) {
console.log(err);
} else {
console.log("Data"+ data)
}
});
}, [])
I will assume you have deployed the cognito federated identity and set
the role policy correctly.
I am used to with this approach to work with federated identity :
AWS.config.update({
region: process.env.REACT_APP_REGION
})
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
'IdentityPoolId': process.env.REACT_APP_USER_POOL_ID
});
const gp = AWS.config.credentials.getPromise();
gp.then(() => {
console.log(AWS.config.credentials.identityId)
const docClient = new AWS.DynamoDB.DocumentClient();
const params = {
TableName: "test_data",
Key: { "id": "Test_2020_11_6_18" },
};
docClient.get(params).promise().then(data => {
console.log("Data" + data)
}).catch(err => {
console.log(err);
})
}).catch((err) => {
console.log(err)
})

I'm trying to query MySQL as a promise, but I keep getting "unhandledpromiserejection error"

Please help I'm trying to deploy my app to App Engine/CloudSQL but I keep getting :
"UnhandledPromiserejectWarning": Cannot enqueue after fatal error..
I'm trying to query MySQL as promise, when I don't I handle the exception it works fine locally, but when I deploy it doesn't work.
How can I handle promise rejection, please Help Thanks
This is db.js
const db = require('./Mysql')
const query = (q, data) => {
return new Promise((resolve, reject) => {
db.query(q, data, (err, res) => (err ? reject(err) : resolve(res)))
})
.then(res => console.log(res))
.catch(err => console.error(err))
This is Mysql.js
{ SQL_SOCKET, SQL_USER, SQL_PASSWORD, SQL_DATABASE } = process.env
const db = mysql.createConnection({
socketPath: SQL_SOCKET,
user: SQL_USER,
password: SQL_PASSWORD,
database: SQL_DATABASE,
charset: 'utf8mb4',
})
module.exports = db
I remember having this problem a few years ago when I tried using the mysql module within an expressJS application and attempted to use async/await. The error could also come from querying on a connection in which a fatal error occured, see here. As such, best practices dictates that on queries, you open a connection, start a query transaction, commit the query and then release the connection afterwards -- allowing you to rollback whenever an error occurs. I do not see this process happening here so it could be a possibility.
In any case, I can provide you with an alternative, which is the method I ended up going with. Basically, I digressed promisifying query() myself and instead let node handle it.
An example of using query without transaction:
/backend/database/database.js
const mysql = require('mysql');
const db = require('../config/config').mysql;
const util = require('util');
const pool = mysql.createPool({
connectionLimit: require('../config/config').cLimit,
host: db.host,
user: db.user,
password: db.password,
database: db.database
});
pool.query = util.promisify(pool.query);
async function query(cmd) {
try {
let result = await pool.query(cmd);
return result;
} catch(error) {
console.error(error);
}
}
module.exports = {
query
};
Which can then be used in your models like such:
/backend/models/User.js
const db = require('../database/database');
async function getUserById(userId) {
const cmd = `SELECT * FROM Users WHERE userId = ${userId}`;
try {
let result = await db.query(cmd);
return result;
} catch(error) {
throw {
message: error
}
}
}
module.exports = {
getUserById
};
Which in turn, can be called from your route handler like such:
/backend/routes/users.js
const router = require('express').Router();
const User = require('../models/User');
router.get('/getUserById/:userId', async (req, res) => {
try {
let user = await User.getUserById(req.params.userId);
res.status(200).send({ user });
} catch(error) {
console.error(error);
res.status(400).send({ error: 'Unable to fetch user' });
}
});
module.exports = router;

No data returned on MongoDB using Express router

I have a Mongo database set up on a Bitnami Lightsail MEAN stack instance that I am trying to connect to with an Angular/Node/Express application that I am building. I have followed the instructions on how to connect and create SSH Port Forwarding from my local machine (https://docs.bitnami.com/aws/infrastructure/mean/).
I am able access localhost:8888, which gives me access to RockMongo that was set up on the MEAN Lightsail instance with my Mongo database. That being said, I think the configuration for the connection to the server from my local machine is fine.
When I run node server and navigate to the URL (http://localhost:3000/api/numbers) for my api GET method, I am not receiving an error on connecting to the database. Instead, I get the following response, which is basically an empty array of data:
{"status":200,"data":[],"message":null}
Here is the code for my api.js file:
const express = require('express');
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
// Connect
const connection = (closure) => {
return MongoClient.connect('mongodb://localhost:27017/sakDB', (err, db) => {
if (err) {
return console.log(err);
}
closure(db);
});
};
// Error handling
const sendError = (err, res) => {
response.status = 501;
response.message = typeof err == 'object' ? err.message : err;
res.status(501).json(response);
};
// Response handling
let response = {
status: 200,
data: [],
message: null
};
// Get numbers
router.get('/numbers', (req, res) => {
connection((db) => {
db.collection('numbers')
.find()
.toArray()
.then((numbers) => {
response.data = numbers;
res.json(response);
})
.catch((err) => {
sendError(err, res);
});
});
});
module.exports = router;
And the code for my router.js file:
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
const api = require('./server/routes/api');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/api', api);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`Running on localhost:${port}`));
I am beginning to think that this is some configuration issue with MongoDB on the MEAN Lightsail instance. If I try to run db.numbers.find() in MongoDB shell, I get the following error:
MongoDB server version: 3.4.7
> db.numbers.find()
Error: error: {
"ok" : 0,
"errmsg" : "not authorized on sakDB to execute command { find: \"numbers\", filter: {} }",
"code" : 13,
"codeName" : "Unauthorized"
}
I have to log in as a user mongo sakDB -u admin -p that I created to in order to find data on the collection.
When I try adding those credentials to the connection string mongodb://admin:PASSWORD#localhost:27017/sakDB, I receive a different authentication error:
name: 'MongoError',
message: 'Authentication failed.',
ok: 0,
errmsg: 'Authentication failed.',
code: 18,
codeName: 'AuthenticationFailed' }
It looks like this issue was related to Bitnami's server configuration with my Express application. It has been resolved.

Resources