Posting to a Neo4j server using node.js - node.js

Disclaimer: This is related to another question I asked here. I was advised to ask a new question rather than to update that one, I hope that this is correct. If not please let me know and ignor this question.
I have been trying to use a Neo4j in Microsoft Azure, using this tutorial. I created a VM running Linux and neo4j. I know his works fine because I have been able to access the database via the web admin portal, where I can create and delete entries. However the problem comes when I try to use node.js to insert elements.
Here is the code for the script:
function insert(item, user, request) {
//comment to trigger .js creation
var neo4j = require('neo4j');
var db = new neo4j.GraphDatabase('http://<username>:<password>#neo4jmobile.cloudapp.net:7474');
var node = db.createNode({ name: item.name });
node.save(function (err, node) {
if (err) {
console.error('Error saving new node to database:', err);
}
else {
console.log('Node saved to database with id:', node.id);
}
});
request.execute();
}
I am getting this error message:
Error saving new node to database: { [Error: connect ETIMEDOUT]
stack: [Getter/Setter],
code: 'ETIMEDOUT',
errno: 'ETIMEDOUT',
syscall: 'connect',
__frame:
{ name: 'GraphDatabase_prototype__getRoot__1',
line: 76,
file: '\\\\10.211.156.195\\volume-0-default\\bf02c8bd8f7589d46ba1\\4906fa4587734dd087df8e641513f602\\site\\wwwroot\\App_Data\\config\\scripts\\node_modules\\neo4j\\lib\\GraphDatabase.js',
prev:
{ name: 'GraphDatabase_prototype_getServices__2',
line: 99,
file: '\\\\10.211.156.195\\volume-0-default\\bf02c8bd8f7589d46ba1\\4906fa4587734dd087df8e641513f602\\site\\wwwroot\\App_Data\\config\\scripts\\node_modules\\neo4j\\lib\\GraphDatabase.js',
prev: [Object],
active: false,
offset: 5,
col: 12 },
active: false,
offset: 5,
col: 12 },
rawStack: [Getter] }
Any help would be appreciated!

Your URL is still wrong: http://<username>:<password>#http://neo4jmobile.cloudapp.net:7474 should be http://<username>:<password>#neo4jmobile.cloudapp.net:7474
In the referenced tutorial (which is quite good btw) he says:
var db = new neo4j.GraphDatabase('http://<username>:<password>#<your neo url>.cloudapp.net:7474');
Where refers to the hostname, i.e.: neo4jmobile

Related

Error:read ECONNRESET - I cannot successfully authenticate with the hp-ux server in node.js

I have a problem with the connection into a hpux server that we host locally in our local network. I get the following error:
Hello world
Connected to Nemesis
true
rejected: Error: read ECONNRESET
at TCP.onStreamRead (node:internal/stream_base_commons:217:20) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read',
level: 'client-socket'
}
node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^
Error: read ECONNRESET
at TCP.onStreamRead (node:internal/stream_base_commons:217:20) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read',
level: 'client-socket'
}
Here is my code:
console.log('Hello world');
const { NodeSSH } = require('node-ssh');
const ssh = new NodeSSH();
ssh.connect({
host: "server",
username: "admin account",
password: "password"
}).then(console.log("Connected to Nemesis"))
console.log(ssh.isConnected());
ssh.exec('hh_client', ['--json'], { cwd: '/', stream: 'stdout', options: { pty: true } }).then(fulfilled => {
console.log("fulfilled:", fulfilled)
}).catch(rejected => {
console.log("rejected:", rejected)
})
I believe it is connecting to the server OK, tested by changing the IP, where I get a message to say that it cannot find the server. That said, the username and password does not seem to be being used, as I can type the user and password wrong, and I get the same error message.
the exec code is just lifted from the npm website for the module.
for a little more context, I am fairly new to hpux and linux in general, as most of this is inherited. I have seen a lot of information about using RSA and public/private keys, but there are already some on the server and I don't want to overwrite anything in the .ssh folder if I can help it.
In terms of connecting via other methods, I can use the username and password using ssh user#server and connect in fine, and do anything I want on the server with full permissions.
Any help appreciated.
Thank you,
Craig
Seing the exact same problem.
It's seems from the logs on the target server that the library is still trying to use key auth, maybe because we are not using it correctly or because it's simply considered insecure by the developers, or maybe they just negleted that option since most people won't use it for security reasons.
Here is the relevant server log:
Jan 23 20:43:55 debian sshd[6152]: error: kex_exchange_identification: banner line contains invalid characters
Jan 23 20:43:55 debian sshd[6152]: banner exchange: Connection from <source_ip_edited_for_privacy> port 42544: invalid format
Here is the code:
const readline = require("readline");
const { NodeSSH } = require("node-ssh");
// function to get input from user
const getInput = () => {
// required to take input from user
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// required to connect
const ssh = new NodeSSH();
rl.question("What is the host? ", (host) => {
console.log(host);
rl.question("What is the user? ", (user) => {
console.log(user);
rl.question("What is the password?", (password) => {
console.log(password);
rl.question("What is the command?", (command) => {
console.log(command);
// Connect
ssh.connect({
host: host,
username: user,
password: password,
//privateKeyPath: '/home/steel/.ssh/id_rsa'
});
// Excute Command
ssh
.execCommand(`${command}`, { cwd: `/home/${user}` })
.then((result) => {
// rl.write(result.stdout);
console.log("STDOUT: " + result.stdout);
console.log("STDERR: " + result.stderr);
})
.catch((err) => {
console.log(err);
})
.finally(() => {
ssh.dispose();
rl.close();
});
});
});
});
});
};
getInput();

Connecting to PostgresSQL hosted online using NodeJS

I'm currently trying to create a functional query from the database to post it into a created a csv file, however I am unable to connect to the PSQL host programmatically. So what I am trying to do is :-
Connect to DB and query results
Push results to an Excel File
Continue()
SFTP Results to myself on SFTP Server and place file in directory.
I am able to connect to the PostgresDB manually by the following in CLI:-
ssh username#xx.xx.xx.xx //Doesnt need password because my id_rsa key is stored on the Server
psql -U username -h LOCALHOST -p 5432 -d databasename pass- password (Manually input)
Furthermore, connecting through Visual Studio Code works as well however I need to connect to the server (Remote Connection) and then connect to the Database using a postgres Driver.
After investigating it, I figured I firstly need to connect using SSH to the server, then and only then I will be allowed to access the Database.
This is how I approached it through Code :-
Index.js
const serverConnectionParams = require('./src/config/serverConn');
function testConnectionServer() {
try {
serverConnectionParams.connectToServer();
} catch (err) {
console.error(err);
}
}
testConnectionServer();
serverConn.js
const { Client } = require('ssh2');
const { readFileSync } = require('fs');
const databaseConnectionParams = require('./databaseConn');
function connectToServer() {
const conn = new Client();
conn.on('ready', () => {
console.log('Client :: ready');
conn.exec('uptime', (err, stream) => {
if (err) throw err;
databaseConnectionParams.auth(); *// This is the database connection param*
stream.on('data', (data) => {
console.log('STDOUT: ' + data);
}).stderr.on('data', (data) => {
console.log('STDERR: ' + data);
});
});
}).connect({
host: 'xx.xx.xx.xx',
username: 'username',
privateKey: readFileSync('src/key/id_rsa')
});
}
exports.connectToServer = connectToServer;
databaseConn.js
const { readFileSync } = require('fs');
const envParam = require('./env.js');
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize(envParam.database, envParam.username, envParam.password, {
host: envParam.host,
dialect: envParam.dialect,
ssl: true,
pool: {
max: envParam.pool.max,
min: envParam.pool.min,
acquire: envParam.pool.aquire,
idle: envParam.pool.idle
}
});
async function auth() {
try {
console.log('trying to connect')
sequelize.validate();
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
exports.auth = auth;
env.js
const env = {
database: 'databasename',
username: 'username',
password: 'password',
host: 'ip#',
dialect: 'postgres',
pool: {
max: 5,
min: 0,
aquire: 30000,
idle: 10000
}
};
module.exports = env;
After running my node index.js I receive the following error statement :-
Client :: ready
trying to connect
STDOUT: 10:43:09 up 1:21, 1 user, load average: 5.71, 6.03, 5.15
C:\Users\~\node_modules\sequelize\lib\dialects\postgres\connection-manager.js:184
reject(new sequelizeErrors.ConnectionError(err));
^
ConnectionError [SequelizeConnectionError]: no pg_hba.conf entry for host "xx.xx.xx.xx", user "username", database "databasename", SSL off
at Client._connectionCallback
{
parent: error: no pg_hba.conf entry for host "xx.xx.xx.xx", user "username", database "databasename", SSL off
at Parser.parseErrorMessage
{
length: 154,
severity: 'FATAL',
code: '28000',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'auth.c',
line: '490',
routine: 'ClientAuthentication'
},
original: error: no pg_hba.conf entry for host "x.x.x.x", user "username", database "password", SSL off
at Parser.parseErrorMessage (C:\Users\~\node_modules\pg-protocol\dist\parser.js:287:98)
at Parser.handlePacket (C:\Users\~\node_modules\pg-protocol\dist\parser.js:126:29)
at Parser.parse (C:\Users\~\node_modules\pg-protocol\dist\parser.js:39:38)
at Socket.<anonymous> (C:\Users\~\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:394:28)
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) {
length: 154,
severity: 'FATAL',
code: '28000',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'auth.c',
line: '490',
routine: 'ClientAuthentication'
}
}
Investigating the Error Code: 28000
Found this link explaining the issue as an authentication attempt failure
https://help.heroku.com/DR0TTWWD/seeing-fatal-no-pg_hba-conf-entry-errors-in-postgres
Also found several solutions online regarding pg_hba.conf needs to use md5 and then restart postgress (Not tried, as i cannot restart the postgress service)
error: Ident authentication failed for user
Found another solution explaining it was an SSL issue (Tried it and it didnt work)
Node.js, PostgreSQL error: no pg_hba.conf entry for host
After using SSL it would change the error code to the following :-
SequelizeConnectionError: self signed certificate
Found a solution to that here:-
SequelizeConnectionError: self signed certificate
After I put that it would give me a different error that rejectUnauthorized is depreciated and very old version (Cant seem to reproduce the error code as of the moment)
So my hands are tied at the moment, any help will be great!
I've also tried using different Javascript modules instead of sequelize however they all have the same authentication issue.
I also tried to pass my id_rsa key, however it wouldnt solve my issue at all.
My assumptions are even though I am passing the connToDatabase function inside the SSH connection, it is still searching for the ip# in the incorrect location. (Ip# of DB on the server is 192.168.31.4)
But when using that IP# it will say ERR Connection Timed out
Another Assumption I have is that the Database has many restrictions from connecting and require further more params.
UPDATE:
I tried editting the pg_hba.conf file through remote access on VSC however it would give me error cannot read file.
Any help would be great!
I had completely forgotten that I posted this question.
The solution to it was pretty straight forward, after investigating it for a while I realized I was making a mistake in connection params.
For others who require help with such issues I will post the solution in a simple manner.
Basically, I needed first to SSH to the server and add a tunnel to my connection to connect to the database. Then and only then will my sequelize params for the database pass through because I have completely connected to the server and internal postgresql database.
So TLDR
SSH -> Tunnel -> Sequelize
ssh(10.x.x.1, etc) -> addTunnel(localhost, etc) -> sequelize(databaseName, etc)
EDIT: Added Code for reference
const Ssh2Promise = require('ssh2-promise');
const { readFileSync } = require('fs');
async function connectToServer(callback) {
const ssh = new Ssh2Promise({
host: '10.x.x.1',
username: 'usernameofssh',
privateKey: readFileSync('src/key/id_rsa'), //This is only for RSA Fingerprint, if you do not have said fingerprint you can use "passphrase" with your password instead
});
const tunnel = await ssh.addTunnel({
remoteAddr: '192.168.0.1', //This is the database connection ip#, once connected to it you can fetch from LOCALHOST. Incase its AWS it would be test.test-test.amazonaws.com
remotePort: 1234, //Port for connection
localPort: 1234,
});
//Don't forget to throw it in a try catch for feedback
await auth(callback); //Send it wherever you need it to go
}

NODEJS - connection to database ECONNREFUSED when using documents.write()

I'm currently studying nodejs and marklogic, I'm running a sample code but I cannot make it work I'm getting econnrefused whenever I run the code.,
Here is my code,
my-connection.js
module.exports = {
connInfo: {
host: 'localhost',
port: 8008,
user: 'user',
password: 'password'
}
};
sample.js
const marklogic = require('marklogic');
const my = require('./my-connection.js');
const db = marklogic.createDatabaseClient(my.connInfo);
const documents = [
{ uri: '/gs/aardvark.json',
content: {
name: 'aardvark',
kind: 'mammal',
desc: 'The aardvark is a medium-sized burrowing, nocturnal mammal.'
}
},
{ uri: '/gs/bluebird.json',
content: {
name: 'bluebird',
kind: 'bird',
desc: 'The bluebird is a medium-sized, mostly insectivorous bird.'
}
},
{ uri: '/gs/cobra.json',
content: {
name: 'cobra',
kind: 'mammal',
desc: 'The cobra is a venomous, hooded snake of the family Elapidae.'
}
},
];
db.documents.write(documents).result(
function(response) {
console.log('Loaded the following documents:');
response.documents.forEach( function(document) {
console.log(' ' + document.uri);
});
},
function(error) {
console.log('error here');
console.log(JSON.stringify(error, null, 2));
}
);
I'm running it by typing node sample.js I'm using marklogic for the database, can someone help me identify the problem here,
I get ECONNREFUSED upon running the app, thank you!
ECONNREFUSED indicates no TCP listener process is running behind localhost:8008. That could mean MarkLogic is not running on your localhost, or it has no app-server configured at port 8008.
Check if http://localhost:8001 works on your machine, and brings up the MarkLogic Admin UI. If so, check the app-servers to see if you actually have one configured for 8008.
HTH!

NODEJS Marklogic - Write document list cannot process response with 404 status when using documents.write()

I'm new to nodejs and marklogic, and I'm following a tutorial for a simple app, I have setup and configured my marklogin login credentials,
when I run this sample code by running node sample.js
the output is write document list cannot process response with 404 status
I wonder why I'm encountering this error,
here is the code from the tutorial,
my-connection.js
module.exports = {
connInfo: {
host: '127.0.0.1',
port: 8001,
user: 'user',
password: 'password'
}
};
sample.js
const marklogic = require('marklogic');
const my = require('./my-connection.js');
const db = marklogic.createDatabaseClient(my.connInfo);
const documents = [
{ uri: '/gs/aardvark.json',
content: {
name: 'aardvark',
kind: 'mammal',
desc: 'The aardvark is a medium-sized burrowing, nocturnal mammal.'
}
},
{ uri: '/gs/bluebird.json',
content: {
name: 'bluebird',
kind: 'bird',
desc: 'The bluebird is a medium-sized, mostly insectivorous bird.'
}
},
{ uri: '/gs/cobra.json',
content: {
name: 'cobra',
kind: 'mammal',
desc: 'The cobra is a venomous, hooded snake of the family Elapidae.'
}
},
];
db.documents.write(documents).result(
function(response) {
console.log('Loaded the following documents:');
response.documents.forEach( function(document) {
console.log(' ' + document.uri);
});
},
function(error) {
console.log('error here');
console.log(JSON.stringify(error, null, 2));
}
);
I hope someone can tell me what is wrong with the code,
Thank You!
The MarkLogic NodeJS Client library is meant to run against a so-called MarkLogic REST-api instance. There is typically one running at port 8000, but you can also deploy other ones at different ports by issuing a POST call to :8002/v1/rest-apis, as described here:
http://docs.marklogic.com/REST/POST/v1/rest-apis
Port 8001 however is reserved for the MarkLogic Admin UI, which doesn't understand the REST calls that the NodeJS Client library is trying to invoke, hence the 404 (not found)..
HTH!

i18next saying key missed always

I am new to Node.js. I want to work with internationalization. I am trying using i18next. I have written this code:
i18n.init({
lng: 'en',
debug: true,
load: ['en', 'ar'],
fallbackLng: 'en',
backend: {
"loadPath": path.join(__dirname,"locale/en/translation.json")
},
getAsync:false
}, (err, t) => {
console.log("this is key value :"+(t("key")));
return t;
});
And in my en/translation.json file I have this contents:
{
key:"hello anil"
}
When I run the program I get this error: i18next::translator: missingKey en translation key key
What went wrong? Please help me out.
Check your debug log.
I found the loadPath is not what I thought, after fixing the path it works.
The reason is my js file is in build directory, so the path becomes build/locales/en.json not /locales/en.json.
the error message,
[Error: ENOENT, open '/opt/www/build/locales/en.json']
errno: 34,
code: 'ENOENT',
path: '/opt/www/build/locales/en.json' } ]
this is my fixed config,
backend: {
loadPath: 'locales/' + '{{lng}}.json',
},

Resources