Node.js and PostgresSQL with Express - node.js

I've written a code to fetch the data from postgres database using express and NODE.js. the database is connected with the backend code but still it is showing error like relation does not exit.
Please check the code and error that I got:
var express = require('express');
var pg = require("pg");
var app = express();
var connectionString = "postgres://postgres:postgres#localhost:5432/testDatabase?currentSchema=testSchema";
app.get('/', function(req, res, next) {
pg.connect(connectionString, function(err, client, done) {
if (err) {
console.log("Not able to get Connection " + err);
res.status(400).send(err);
} else {
console.log("Connected.!");
}
const
query = {
// give the query a unique name
name : 'fetch-user-details',
text : 'SELECT * FROM loginTable',
}
client.query(query, function(err, result) {
done(); // closing the connection;
if (err) {
console.log(err);
res.status(400).send(err);
}
res.status(200).send(result.rows);
});
});
});
app.listen(4000, function() {
console.log('Server is running.. on Port 4000');
});
and the error response that I got is like:
Server is running.. on Port 4000
Connected.!
{ error: relation "logintable" does not exist
at Connection.parseE (C:\Users\sumit_srivastava\Desktop\Java_WorkSpace\SimpleNodeAppln\node_modules\pg\lib\connection.js:554:11)
at Connection.parseMessage (C:\Users\sumit_srivastava\Desktop\Java_WorkSpace\SimpleNodeAppln\node_modules\pg\lib\connection.js:381:17)
at Socket.<anonymous> (C:\Users\sumit_srivastava\Desktop\Java_WorkSpace\SimpleNodeAppln\node_modules\pg\lib\connection.js:117:22)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at Socket.Readable.push (_stream_readable.js:208:10)
at TCP.onread (net.js:594:20)
name: 'error',
length: 120,
severity: 'ERROR',
code: '42P01',
detail: undefined,
hint: undefined,
position: '15',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'src\\backend\\parser\\parse_relation.c',
line: '986',
routine: 'parserOpenTable' }

just run this db dump at my Postgres
CREATE SCHEMA "testSchema";
ALTER SCHEMA "testSchema" OWNER TO postgres;
SET search_path = "testSchema", pg_catalog;
SET default_tablespace = '';
SET default_with_oids = false;
CREATE TABLE "loginTable" ( "ID" numeric NOT NULL, "Name" text );
ALTER TABLE "loginTable" OWNER TO postgres;
this was the problem
change your query to this
query = {
// give the query a unique name
name : 'fetch-user-details',
text : `SELECT * FROM "testSchema".logintable`,
}
you should mention the schema name
tasted on
Ubuntu
postgres 10.6
pg: 6.4.2
node v10.14.1

Related

Problem connecting postgreSQL with Knex - assert.fail(`unknown message code: ${code.toString(16)}`)

I'm totally new to relational databases and I'm trying to build a node and express project with postgres using knex.
I'm getting the following error when trying to connect to postgres:
/home/German/Desktop/ger/code/projects/mixr/mixr-back/node_modules/pg-protocol/src/parser.ts:202
assert.fail(`unknown message code: ${code.toString(16)}`)
^
AssertionError [ERR_ASSERTION]: unknown message code: 5b
at Parser.handlePacket (/home/German/Desktop/ger/code/projects/mixr/mixr-back/node_modules/pg-protocol/src/parser.ts:202:16)
at Parser.parse (/home/German/Desktop/ger/code/projects/mixr/mixr-back/node_modules/pg-protocol/src/parser.ts:103:30)
at Socket.<anonymous> (/home/German/Desktop/ger/code/projects/mixr/mixr-back/node_modules/pg-protocol/src/index.ts:7:48)
at Socket.emit (node:events:394:28)
at Socket.emit (node:domain:475:12)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at TCP.onStreamRead (node:internal/stream_base_commons:199:23) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: undefined,
expected: undefined,
operator: 'fail'
}
I understand it's a connection problem, but I'm not sure why I'm getting this.
This is my connection code:
export const knex = require('knex')({
client: 'pg',
connection: {
host : 'localhost',
port : 3306,
user : 'notTheRealUser',
password : 'notTheRealPassword',
database : 'pgdb'
}
})
knex.raw("SELECT 1").then(() => {
console.log("PostgreSQL connected")
})
.catch((e: Error) => {
console.log("PostgreSQL not connected")
console.error(e)
})
And then I'm importing the Knex object on the different routes to make queries, like so:
import { knex } from '../db/db'
router.post('/register', async (req: Request, res: Response) => {
// Check if the email isn't already taken
try {
const emailIsTaken = await knex('users').where({ email: req.body.email })
if (emailIsTaken) return res.status(500).json('Email already used')
} catch (err) {
res.status(500).send(err)
console.error(err)
}
})
Full code can be found here: https://github.com/coccagerman/mixr-back
you are using MySQL port 3306,
PostgresQL uses port 5432

node.js is not connecting to SQL Server database using SQL Server authentication

I'm using node.js and the mssql package to connect to a SQL Server database using SQL Server authentication. When I try connecting using SQL Server Management Studio with the same credentials, it is working fine. However, with node.js, I cannot login and get an error code ELOGIN with connection error.
I've tried many examples shown in google and I'm facing the same issue.
Let me know what I'm missing. Here is the code snippet of mine.
Code starts here
var sql = require('mssql');
var config = {
server: 'scaXXXXXXXXXXXX',
database: 'scaXXXXXXXXXX',
user: 'svcXXXXXXX',
password: 'Password',
port: 1433
};
function listProducts() {
var conn = new sql.ConnectionPool(config);
conn.connect().then(function () {
var request = new sql.Request(conn);
request.query("select top 1 * from dbo.Persons").then(function
(recordSet) {
console.log(recordSet);
conn.close();
}).catch(function (err) {
console.log(err);
conn.close();
});
}).catch(function (err) {
console.log(err);
});
}
listProducts();
This is the error while running this code:
ConnectionError: Login failed for user 'svcXXXXXXX'.
at Connection.tedious.once.err (C:\aws\node_modules\mssql\lib\tedious.js:244:17)
at Object.onceWrapper (events.js:277:13)
at Connection.emit (events.js:189:13)
at Connection.processLogin7Response (C:\aws\node_modules\tedious\lib\connection.js:1397:14)
at Connection.message (C:\aws\node_modules\tedious\lib\connection.js:1932:14)
at Connection.dispatchEvent (C:\aws\node_modules\tedious\lib\connection.js:1084:36)
at MessageIO.messageIo.on (C:\aws\node_modules\tedious\lib\connection.js:984:14)
at MessageIO.emit (events.js:189:13)
at Message.message.on (C:\aws\node_modules\tedious\lib\message-io.js:32:14)
at Message.emit (events.js:194:15)
code: 'ELOGIN',
originalError: { ConnectionError: Login failed for user 'svcXXXXXXX'.
at ConnectionError (C:\aws\node_modules\tedious\lib\errors.js:13:12)
at Parser.tokenStreamParser.on.token (C:\aws\node_modules\tedious\lib\connection.js:735:29)
at Parser.emit (events.js:189:13)
at Parser.parser.on.token (C:\aws\node_modules\tedious\lib\token\token-stream-parser.js:27:14)
at Parser.emit (events.js:189:13)
at addChunk (C:\aws\node_modules\readable-stream\lib_stream_readable.js:297:12)
at readableAddChunk (C:\aws\node_modules\readable-stream\lib_stream_readable.js:279:11)
at Parser.Readable.push (C:\aws\node_modules\readable-stream\lib_stream_readable.js:240:10)
at Parser.Transform.push (C:\aws\node_modules\readable-stream\lib_stream_transform.js:139:32)
at doneParsing (C:\aws\node_modules\tedious\lib\token\stream-parser.js:80:14)
message: 'Login failed for user \'svcXXXXXXX\'.',
code: 'ELOGIN' }, name: 'ConnectionError' }
I expect one record from database should extract and display.
it looks your login information is not correct.
did you write proper user name and password?
if your login info is correct, then check out login info has authority to be connected from the external environment
Try this out. It worked for me. If you are not doing with a localhost Database you need to be in that network. Make sure you can ping the database server.
var sql = require("mssql");
var moment = require("moment");
let port = process.env.PORT;
if (port == null || port == "") {
port = 8000;
}
var config = {
user: "xxxx",
password: "xxxxx",
server: "xxxxxx",
database: "xxxx"
};
const dbconn = sql.connect(config, err => {
if (!err) {
console.log("Connected to the database");
} else {
console.log("Problem in connecting to database");
console.log(err);
console.log("testing ");
}
});
app.get("/getSummaryDetails", (req, res) => {
dbconn.query("exec QCGrid", (err, rows, fields) => {
if (!err) {
res.send(rows.recordsets[0]);
}
});
});

Unable to connect to Microsoft SQL Server using Node.js,mssql and express

I am trying to learn Node.js and created a simple project to query the local database. But I get failed to look up an instance error message.
I have checked that the SQL Server services running in services.msc
I have verified TCP/IP is enabled
I have tried with the username and password and without it as well. I connect to localdb in SQL Server Management Studio as (localdb)\v11.0 and below is the screenshot of the properties
What am I doing incorrectly? What should be actual username and password? What should be the servername?
const sql = require('mssql');
// config for your database
const config = {
user: 'mywindows username',
password: 'my windows password',
server: '(localdb)\\v11.0',
database: 'test',
options: {
encrypt: true
}
};
console.log('starting sql');
var connection = new sql.connect(config, function(err) {
console.log(err);
var request = new sql.Request(connection);
request.query('select * from employees', function(err, recordset) {
if(err) // ... error checks
console.log('Database connection error');
console.dir("User Data: "+recordset);
});
});
sql.close();
console.log('ending sql');
});
app.listen(3002, () => {
console.log('Listening on port 3002');})
Below is the error message
{ ConnectionError: Failed to lookup instance on (localdb) -
getaddrinfo ENOTFOUND (localdb)
at Connection.tedious.once.err (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\mssql\lib\tedious.js:244:17)
at Object.onceWrapper (events.js:285:13)
at Connection.emit (events.js:197:13)
at InstanceLookup.instanceLookup (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\connection.js:945:16)
at sender.execute (C:\Users\vndbsubramaniam\Desktop\React projects\ReactWithSql\node_modules\tedious\lib\instance-lookup.js:66:13)
at GetAddrInfoReqWrap.invokeLookupAll [as callback] (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\sender.js:43:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:70:17) code: 'EINSTLOOKUP', originalError: { ConnectionError: Failed to
lookup instance on (localdb) - getaddrinfo ENOTFOUND (localdb)
at ConnectionError (C:\Users\vndbsubramaniam\Desktop\React projects\ReactWithSql\node_modules\tedious\lib\errors.js:13:12)
at InstanceLookup.instanceLookup (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\connection.js:945:32)
at sender.execute (C:\Users\vndbsubramaniam\Desktop\React projects\ReactWithSql\node_modules\tedious\lib\instance-lookup.js:66:13)
at GetAddrInfoReqWrap.invokeLookupAll [as callback] (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\sender.js:43:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:70:17)
message:
'Failed to lookup instance on (localdb) - getaddrinfo ENOTFOUND (localdb)',
code: 'EINSTLOOKUP' }, name: 'ConnectionError' } Database connection error
After struggling for hours on this one finally found the answer here SQL to Node connection
It seems i have to add msnodesqlv8 package and use add the driver syntax to the config.
app.get('/test', (req, res) => {
const sql = require('mssql/msnodesqlv8');
// config for your database
const config = {
database: 'test',
server: '(localdb)\\v11.0',
driver: 'msnodesqlv8',
options : {
trustedConnection : true
}
};
console.log('starting sql');
const pool = new sql.ConnectionPool(config);
pool.connect().then(() => {
//simple query
pool.request().query('select * from employees', (err, result) => {
if(err) res.send(err)
else{
return res.json({
data : result.recordset
})
}
})
sql.close();
})
console.log('ending sql');
});
you will need msnodesqlv8 driver, which you have to paste it in require as
var sql = require('mssql/msnodesqlv8'),
as well as you will have to include it in driver section in config object.
var config = {
user:"*****",
password:"*****",
database:"*****",
driver: 'msnodesqlv8',
server:"*****",
options: {
trustedConnection : true
}
}

Error: column "undefined" does not exist

Hy everyone
I'm a new developer ReactJS. I tried to set up Firebase into my backend and I've a problem with my frontend. If I'm running my API using a postman, my API work and send a message from my backend but if I running my code from frontend I got error like this Column in the table is users and is not undefined
{ error: column "undefined" does not exist
at Connection.parseE (C:\fordg\node_modules\pg\lib\connection.js:567:11)
at Connection.parseMessage (C:\fordg\node_modules\pg\lib\connection.js:391:17)
at Socket.<anonymous> (C:\fordg\node_modules\pg\lib\connection.js:129:22)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at TCP.onread (net.js:547:20)
name: 'error',
length: 109,
severity: 'ERROR',
code: '42703',
detail: undefined,
hint: undefined,
position: '55',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_relation.c',
line: '3183',
routine: 'errorMissingColumn' }
and this is my backend code
Orders.patch([ Object.assign({id: req.params.id}, req.body) ])
.then(orders => {
DB.query("SELECT oauth FROM users WHERE id = "+req.body.driver+" OR id = "+req.body.customer+"").then(res=>{
res.map((row,i)=>{
let tmp = {
token: row.oauth.token
}
res[i] = tmp;
});
// console.log(res);
const arrayToken = res.map(function (obj) {
return obj.token;
});
// console.log(arrayToken);
const message = {
// to: res[0].token,
registration_ids: arrayToken,
notification: {
body: "Hey! you got update order notification."
}
};
fcm.send(message, function(err, response){
console.log(response);
})
}).catch(err => console.log(err));
jsonData = util.jsonData(null, orders);
res.json(jsonData);
})
.catch(err => {
jsonData = util.jsonData(400);
res.status(jsonData.code).json(jsonData);
})
})
So how to fixed it and can you help me explain error of my code ?
Error is here
WHERE id = "+req.body.driver+" OR id = "+req.body.customer+"
You need to use defined variables in this scope

How to drop a database in postgres sql using node.js?

I am trying to drop a database called test from node.js postgres sql but it is not working.
var express = require('express');
var app = express();
var pg = require('pg');
var pgp = require('pg-promise')();
// Connect to PostgreSQL database
var connectionString = process.env.DATABASE_URL || 'postgres://postgres:pass123#localhost:5432/test';
var db = pgp(connectionString);
db.connect();
db.query("DROP DATABASE test").then(function()
{
//createDatabases(db);
}).catch(function(err)
{
console.log(err);
});
But I am getting an error
{ [error: cannot drop the currently open database]
name: 'error',
length: 87,
severity: 'ERROR',
code: '55006',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'dbcommands.c',
line: '834',
routine: 'dropdb' }
Does anyone know how to fix it?
Thanks
As the error says, you can't be connected to the DB in question to drop it. You can connect to a different DB in order to do so, or use a tool like pgtools
var pgtools = require('pgtools');
// This can also be a connection string
// (in which case the database part is ignored and replaced with postgres)
const config = {
user: 'postgres',
password: 'some pass',
port: 5432,
host: 'localhost'
}
pgtools.dropdb(config, 'test-db', function (err, res) {
if (err) {
console.error(err);
process.exit(-1);
}
console.log(res);
});

Resources