Write ECONNRESET error - node.js

I watched some possible answers to my problem but I can't find a way to solve it.
When I call localhost:3000/users/create_account, I have an error ECONNRESET.
It concerns this service:
router.post('/create_account', function (req, res, next) {
const results = [];
client.connect();
// Grab data from http request
const data = {
username: req.body.username, name: req.body.user,
firstname: req.body.firstname, email: req.body.email,
location: req.body.location
};
// Get a Postgres client from the connection pool
client.connect('error', function (err, data) {
// Handle connection errors
if (err) {
done();
console.log(err);
return res.status(500).json({ success: false, data: err });
}
const queryInsert = 'INSERT INTO Users(username, name,'
+ 'firstname, email, location) values($1, $2, $3, $4, $5)';
const values = [data.username, data.name,
data.firstname, data.email, data.location];
// SQL Query > Insert Data into Users
client.query(queryInsert, values, (err, res) => {
if (err) {
console.log(err.stack)
} else {
query.on('end', () => {
done();
Promise.all([queryInsert])
.then(() => client.end()).catch(err => console.log(err));
return res.json(results);
});
};
});
Is someone have an idea of what causes that and how to resolve this problem, please?
This is the complete error:
Error: write ECONNRESET
at _errnoException (util.js:992:11)
at Socket._writeGeneric (net.js:764:25)
at Socket._write (net.js:783:8)
at doWrite (_stream_writable.js:397:12)
at writeOrBuffer (_stream_writable.js:383:5)
at Socket.Writable.write (_stream_writable.js:290:11)
at Socket.write (net.js:707:40)
at Connection._send (C:\Users\Amaris\Desktop\NodeJS_Projects\basefugees-dev-backend\node_modules\pg\lib\connection.js:198:24)
at Connection.password (C:\Users\Amaris\Desktop\NodeJS_Projects\basefugees-dev-backend\node_modules\pg\lib\connection.js:190:8)
at C:\Users\Amaris\Desktop\NodeJS_Projects\basefugees-dev-backend\node_modules\pg\lib\client.js:98:9
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! basefugees-dev-backend#0.0.1 start: `node ./bin/www node`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the basefugees-dev-backend#0.0.1 start script.
npm ERR! This is probably not a problem with npm. There is likely additional
logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Amaris\AppData\Roaming\npm-cache\_logs\2018-07- 11T14_05_26_893Z-debug.log
And my package.json:
{
"name": "basefugees-dev-backend",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node ./bin/www node",
"database": "node ./models/database",
"test": "mocha"
},
"dependencies": {
"body-parser": "^1.18.3",
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"dotenv": "^6.0.0",
"express": "~4.16.0",
"http-errors": "~1.6.2",
"morgan": "~1.9.0",
"pg": "^6.1.0",
"pg-hstore": "^2.3.2"
},
"devDependencies": {
"chai": "^4.1.2",
"mocha": "^5.2.0"
}
}

You don't seem to be following the correct API for error handling. From the docs, there is no overload of client.connect() that takes a string as the first parameter. It may be attempting to use that value as a password or other config value based on the error stack.
What you want to use instead is:
client.on('error', (err) => {
// do whatever. Though again you're calling a `done` that doesn't seem defined, and some other concerns.
});

Related

How to connect Redshift database using Node JS

I am not able to connect to the redshift database using Node. I am using Node JS version 14.15.1.
Is there any issue related to this version?
The following code, I have tried in my local machine,
redshift.js file
var Redshift = require('node-redshift');
var client = {
user: 'user',
database: 'db',
password: 'password',
port: port,
host: 'hostname',
};
var redshiftClient = new Redshift(client, {rawConnection:true});
module.exports = redshiftClient;
The following is the code to get the values from database,
index.js file
var redshiftClient = require('./redshift.js');
console.log('Before Connection');
redshiftClient.connect(function(err){
console.log('After Connection');
if(err) throw err;
else{
redshiftClient.query('SELECT * FROM "customer"', {raw: true}, function(err, data){
if(err) throw err;
else{
console.log(data);
redshiftClient.close();
}
});
}
});
If I run this code not getting the error and even this line is also not executed console.log('After Connection');
The package seems a bit abandoned as here's an open issue with exact issue
To solve that you need to apply this solution manually
go to node_modules/node-redshift and replace
"dependencies": {
"commander": "^2.9.0",
"migrate": "^0.2.2",
"pg": "^6.1.2",
"sql-bricks": "^1.2.3"
},
in package.json to
"dependencies": {
"commander": "^2.9.0",
"migrate": "^0.2.2",
"pg": "^8.1.5",
"sql-bricks": "^1.2.3"
},
run npm install in this directory in order to update this package. After that your code will work
This library is not very active, as mentioned above there's an open issue in github from 2020.
It's better to use pg-promise
Attaching a script link here.
https://www.javaniceday.com/post/how-to-connect-to-a-redshift-database-from-node-js

loopback nodejs server not starting

I have project with nodejs loopback 3.x version and I am recently turned dev in nodejs. I have written the models, server aspects (server.js, server/root.js) etc. Following are the dependencies:
"dependencies" : {
"#types/async": "2.0.40",
"#types/lodash": "4.14.139",
"#types/loopback": "3.1.3",
"#types/loopback-boot": "2.23.0",
"loopback-connector-rest": "3.0.0",
"loopback-model-binder": "1.4.0",
"#types/multiparty": "0.0.31",
"rimraf": "2.6.1",
"sinon": "3.2.1",
"ts-node": "3.3.0",
"typescript": "2.8.3",
"gulp-sequence": "0.4.6",
"gulp-symlink": "2.1.4",
"gulp-typescript": "4.0.1",
"request": "2.81.0",
"shelljs": "0.8.1",
"yargs": "11.0.0",
"os-locale": "3.1.0",
"loopback-connector": "4.4.0",
"strong-globalize": "2.10.0",
"strong-remoting": "3.14.0"
}
This is my code snippet in server.ts:
const app: any = loopback();
boot(app, __dirname, (err) => {
if (err) throw err;
});
app.start = () => {
return app.listen(() => {
const BASE_URL = app.get('url').replace(/\/$/, '');
const explorer = app.get('loopback-component-explorer');
if (explorer) {
Logger.info(`Browse your REST API at ${BASE_URL}${explorer.mountPath}`);
}
});
};
Following are the steps for installing and starting app:
npm install
npm run build
npm run start
But the application is not starting, no errors but returns at command prompt. I enabled the verbose output for the npm run start -verbose command and I found following:
loopback:datasource Module ./connectors/rest not found, will try another candidate. +10ms
loopback:datasource Initializing connector RequestBuilder +561ms
loopback:datasource Connector is initialized for dataSource rest +7ms
loopback:datasource DataSource rest is now connected to undefined +1ms
lifecycle port-app#2.0.0~start: unsafe-perm in lifecycle true
Please let me know about any pointers regarding the above issue.
it was a silly miss from my part. Once you create the app and then in boot process you need to start the application.
boot(app, __dirname, (err) => {
if (err) throw err;
app.start(); // <-- Fix
});

Deploy Express server and test GraphQL API via CircleCI

I wish to test that my Express server launches properly and that my endpoint retrieves the correct information. I wish to do this in CI so that I can monitor when my application is no longer working, if I make any changes in the future.
It's a very simple application, my server looks like this:
server.js
import express from 'express';
import graphqlHTTP from 'express-graphql';
import { GraphQLObjectType, GraphQLString, GraphQLSchema } from 'graphql';
import cors from 'cors';
const QueryRoot = new GraphQLObjectType({
name: 'Query',
fields: () => ({
hello: {
type: GraphQLString,
resolve: () => "Hello world!"
}
})
});
const schema = new GraphQLSchema({ query: QueryRoot });
const app = express();
app.use(cors()); // enable cors
app.use('/api', graphqlHTTP({
schema: schema,
graphiql: true,
}));
app.listen(1337, () => {
console.log('Server running on port: 1337');
});
basicTest.test.js:
const chai = require('chai');
const expect = chai.expect;
const url = `http://localhost:1337`;
const request = require('supertest')(url);
describe('GraphQL', () => {
it('Response returns hello world', (done) => {
request.post('/api')
.send({ query: ' { hello }' })
.expect(200)
.end((err, res) => {
if (err) return done(err);
expect(res.body.data.hello).to.contain('Hello world!');
done();
});
});
});
My .circleci/config.yml looks like this:
# Javascript Node CircleCI 2.0 configuration file
#
# Check https://circleci.com/docs/2.0/language-javascript/ for more details
#
version: 2
jobs:
build:
docker:
# specify the version you desire here
- image: circleci/node:10.16.0
# Specify service dependencies here if necessary
# CircleCI maintains a library of pre-built images
# documented at https://circleci.com/docs/2.0/circleci-images/
# - image: circleci/mongo:3.4.4
working_directory: ~/repo
steps:
- checkout
# Download and cache dependencies
- restore_cache:
keys:
- v1-dependencies-{{ checksum "package.json" }}
# fallback to using the latest cache if no exact match is found
- v1-dependencies-
- run: npm install
- save_cache:
paths:
- node_modules
key: v1-dependencies-{{ checksum "package.json" }}
- run:
npm start &
npm test
and package.json:
{
"name": "graphql-express-server",
"repository": {
"url": "myURL"
},
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon -r esm server.js",
"test": "mocha test/*.test.js"
},
"author": "AuthorName",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"esm": "^3.2.25",
"express": "^4.17.1",
"express-graphql": "^0.9.0",
"graphql": "^14.4.2",
"nodemon": "^1.19.1",
"supertest": "^4.0.2"
},
"devDependencies": {
"chai": "^4.2.0",
"mocha": "^6.2.0"
}
}
I tried adding & to the end of my npm start command but that just skips the entire process as far as I can see. The issue I'm getting is 'Error: ECONNREFUSED: Connection refused' when the test gets executed.
Do I need to host the server elsewhere? I'm unsure what I'm supposed to do. I've never really tested the back end in CI before.
EDIT:
My commands are as follows:
- run:
npm start &
- run:
sleep 5
- run:
npm test
And my output in CI is as follows:
--------------------------------
***npm start &***
#!/bin/bash -eo pipefail
npm start &
--------------------------------
***sleep 5***
#!/bin/bash -eo pipefail
sleep 5
--------------------------------
***npm test***
#!/bin/bash -eo pipefail
npm test
> graphql-express-server#1.0.0 test /home/circleci/repo
> mocha test/*.test.js
GraphQL
1) Response returns hello world
0 passing (14ms)
1 failing
1) GraphQL
Response returns hello world:
Error: ECONNREFUSED: Connection refused
at Test.assert (node_modules/supertest/lib/test.js:165:15)
at localAssert (node_modules/supertest/lib/test.js:131:12)
at /home/circleci/repo/node_modules/supertest/lib/test.js:128:5
at Test.Request.callback (node_modules/superagent/lib/node/index.js:728:3)
at ClientRequest.req.once.err (node_modules/superagent/lib/node/index.js:647:10)
at Socket.socketErrorListener (_http_client.js:392:9)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
npm ERR! Test failed. See above for more details.
Exited with code 1
--------------------------------
As you can see, the message Server running on port: 1337 does not show up in my npm start & step console section.
Any suggestions? Am I doing something wrong?
npm start & won't wait for server to start, are you sure your server is listening on the port by the time your test makes a request? I.e. do you have 'Server running on port: 1337' in your console on CI? If not then try running sleep 3 before starting tests

NodeJS, MongoDB, Jade/Pug - Cannot read property 'length' of undefined on Apache(localhost works)

I'm having some trouble to connect my app in the server(hosted by KingHost)..
On local machine, it works perfectly
On the server, the one thing I do is change the database from localhost to the server, and the port from 3000 to my server...
When I run the app on the server I get:
TypeError: /home/rsracingufrgs/apps_nodejs/views/index.jade:316
314| h3.section-heading Capitão
315| .row
> 316| each membro, i in capitao
317| .col-sm-4
318| .team-member
319| img.mx-auto.rounded-circle(src='/img/team/#{membro.imagem}', alt='#{membro.nome}')
Cannot read property 'length' of undefined
at eval (eval at <anonymous> (/home/rsracingufrgs/apps_nodejs/node_modules/jade/lib/index.js:218:8), <anonymous>:1755:31)
at eval (eval at <anonymous> (/home/rsracingufrgs/apps_nodejs/node_modules/jade/lib/index.js:218:8), <anonymous>:1888:4)
at eval (eval at <anonymous> (/home/rsracingufrgs/apps_nodejs/node_modules/jade/lib/index.js:218:8), <anonymous>:6670:22)
at res (/home/rsracingufrgs/apps_nodejs/node_modules/jade/lib/index.js:219:38)
at Object.exports.renderFile (/home/rsracingufrgs/apps_nodejs/node_modules/jade/lib/index.js:380:38)
at Object.exports.renderFile (/home/rsracingufrgs/apps_nodejs/node_modules/jade/lib/index.js:370:21)
at View.exports.__express [as engine] (/home/rsracingufrgs/apps_nodejs/node_modules/jade/lib/index.js:417:11)
at View.render (/home/rsracingufrgs/apps_nodejs/node_modules/express/lib/view.js:127:8)
at tryRender (/home/rsracingufrgs/apps_nodejs/node_modules/express/lib/application.js:640:10)
at EventEmitter.render (/home/rsracingufrgs/apps_nodejs/node_modules/express/lib/application.js:592:3)
But on localhost it works perfectly...
The databases are equal(see image below)
The code(what changes between server and localhost)
var db = monk('localhost:27017/rsracingufrgs') //localhost
//var db = monk('mongodb.rsracingufrgs.com.br/rsracingufrgs01'); //server
var porta = 3000 // localhost
//var porta = 21031 //server
The call to the database:
router.get('/', function (req, res, next) {
const db = req.db;
const async = require("async")
const names = ['capitao',...]
const collections = names.map(name => db.get(name) )
const functions = collections.map(collection => {
return done => collection.find( {}, done )
})
async.series( functions, (err, results) => {
// "results" is now an array containing [ docs1, docs2, .. ]
res.render('index', {
env: env,
capitao: results[0],
...
});
})
});
the Jade code(works on localhost):
.row
each membro, i in capitao
.col-sm-4
.team-member
img.mx-auto.rounded-circle(src='/img/team/#{membro.imagem}', alt='#{membro.nome}')
h4 #{membro.nome}
p.text-muted #{membro.curso}
ul.list-inline.social-buttons
li.list-inline-item
a(href="mailto:#{membro.email}")
i.fa.fa-envelope
Other things that could be important:
node version: 6.11.1
npm version: 3.10.10
mongodb version(installed from npm on server): 2.2.31
Dependencies from package.json
"dependencies": {
"async": "^2.5.0",
"body-parser": "^1.18.1",
"connect-ensure-login": "^0.1.1",
"cookie-parser": "^1.4.3",
"dotenv": "^4.0.0",
"express": "^4.15.4",
"express-session": "^1.15.5",
"jade": "^1.11.0",
"logger": "0.0.1",
"mongo": "^0.1.0",
"mongodb": "^2.2.31",
"mongoose": "^4.11.11",
"monk": "^6.0.4",
"morgan": "^1.8.2",
"passport": "^0.4.0",
"passport-auth0": "^0.6.0",
"path": "^0.12.7",
"request": "^2.81.0"
}
Edit: using the debug code that #Sridhar provided, I got the following result:
{ MongoError: not authorized on rsracingufrgs01 to execute command { find: "capitao", filter: {}, projection: {} }
at Function.MongoError.create (/home/rsracingufrgs/apps_nodejs/node_modules/mongodb-core/lib/error.js:31:11)
at queryCallback (/home/rsracingufrgs/apps_nodejs/node_modules/mongodb-core/lib/cursor.js:212:36)
at /home/rsracingufrgs/apps_nodejs/node_modules/mongodb-core/lib/connection/pool.js:469:18
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
name: 'MongoError',
message: 'not authorized on rsracingufrgs01 to execute command { find: "capitao", filter: {}, projection: {} }',
ok: 0,
errmsg: 'not authorized on rsracingufrgs01 to execute command { find: "capitao", filter: {}, projection: {} }',
code: 13 }
Update
As per mongodb error codes, 13 corresponds to Unauthorized. You can check MongoDB not authorized for query - code 13 for fixing it.
Original answer
Cannot read property 'length' of undefined
It clearly states that .length is called on the undefined variable. So, I suspect your result[0] will be undefined. If you log results, you will know more about the issue.
'use strict';
let _ = require('lodash');
....
async.series(functions, (err, results) => {
if (err || _.isUndefined(results)) {
//general error handling
console.log(err);
return res.render('index', {
env: env,
capitao: []
});
}
res.render('index', {
env: env,
capitao: _.isUndefined(results[0]) ? [] : result[0],
...
});
});
Your value is undefined so only It's through that error. so, please check that value is not undefined before accessing the length property on that variable.

Pact exited with code 1

I'm trying to execute some tests with Pact library and I'm getting some errors. Here is the test configuration:
const path = require('path');
const Pact = require('pact');
const expect = require('expect.js');
const config = require('../../../src/server/config');
const service = require('../../../src/routes/interactions/interactions.service');
describe('#component/interactions tests', () => {
const url = 'http://localhost';
const port = 8989;
const provider = Pact({
port: port,
log: path.resolve(process.cwd(), 'test/component/interactions/log/interactions-pact.log'),
dir: path.resolve(process.cwd(), 'test/component/interactions/pacts'),
spec: 2,
consumer: 'cx_issue',
provider: 'interaction',
// logLevel: 'WARN'
});
config.settingsToExport.INTERACTION_URL = `${url}:${port}`;
before(done => {
provider.setup()
.then(() => {
done();
})
.catch(err => {
done(err);
});
});
after(done => {
provider.finalize()
.then(() => {
done();
})
.catch(err => {
done(err);
});
});
describe('#createInteraction', () => {
before(done => {
const INTERACTION_BODY = {
contact: 'contact1'
};
const TERM = {
generate: '0dae5b93-9451-4b08-b7bb-f0b944fbcdf2',
matcher: '^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
};
const pactInteractionCreate = {
state: 'Creates a new interaction',
uponReceiving: 'a new interaction is created successfully',
withRequest: {
method: 'POST',
path: '/interactions',
body: INTERACTION_BODY
},
willRespondWith: {
status: 201,
body: {
id: Pact.Matchers.term(TERM)
}
}
};
const promises = [
provider.addInteraction(pactInteractionCreate)
];
Promise.all(promises)
.then(() => {
done();
});
});
it('/api/interactions POST', done => {
const interaction = {
contact: 'The xx'
};
service.createInteraction(interaction)
.then(response => {
expect(response.id).to.be.equal(TERM.generate);
done();
})
.catch(done);
});
});
});
This is my package.json file content, with all dependencies I've installed:
{
"name": "issueAPI",
"version": "1.0.0",
"private": true,
"main": "./src/index.js",
"scripts": {
"dev": "nodemon -e js ./src/index.js",
"start": "node ./src/index.js",
"linter": "node ./node_modules/eslint/bin/eslint.js ./src",
"test": "mocha test",
"test-component": "mocha test/component",
"install-test-build": "npm install && npm test && npm run linter",
"test-build": "npm test && npm run linter"
},
"jshintConfig": {
"esversion": 6
},
"dependencies": {
"ajv": "^4.11.3",
"body-parser": "^1.17.2",
"express": "^4.15.3",
"express-winston": "^2.4.0",
"request": "^2.81.0",
"winston": "^2.3.1",
"yamljs": "^0.2.9"
},
"devDependencies": {
"#pact-foundation/pact-node": "^4.8.3",
"dotenv": "^4.0.0",
"eslint": "^4.2.0",
"eslint-config-node": "^1.6.0",
"expect.js": "^0.3.1",
"mocha": "^3.2.0",
"nodemon": "^1.11.0",
"pact": "^2.3.3",
"sinon": "^2.3.8",
"supertest": "^3.0.0"
}
}
And this is the error I get:
Basically, right now I don't mind at all if the tests are well or not. The main problem right now is that the pact mock server is not being started.
The weird thing here is that I have other project where the pact tests run properly. I've moved the service I want to test from the project where is failing to the one which executes those tests fine, and it is working (at least the pact mock server is launched). The dependencies in this other project are almost the same as the problemathic project:
"dependencies": {
"ajv": "^4.11.3",
"body-parser": "^1.16.1",
"dotenv": "^4.0.0",
"express": "^4.14.0",
"jsonwebtoken": "^7.4.1",
"jwt-simple": "^0.5.1",
"morgan": "^1.8.1",
"mustache-express": "^1.2.4",
"node-env-file": "^0.1.8",
"request": "^2.79.0",
"when": "^3.7.8"
},
"devDependencies": {
"#pact-foundation/pact-node": "^4.8.3",
"eslint": "^3.17.1",
"eslint-config-node": "^1.6.0",
"expect.js": "^0.3.1",
"mocha": "^3.2.0",
"nodemon": "^1.11.0",
"pact": "^2.3.3",
"sinon": "^1.17.7",
"supertest": "^3.0.0",
"nock": "^9.0.13"
}
What's going on with this situation?
EDIT: I've launched the pact tests with DEBUG flag and this is the log generated:
It looks like the server is unable to start up correctly, judging by the exit code of 1. This could be a port conflict on port 8989, so that's worth checking.
It could be related to https://github.com/pact-foundation/pact-js/issues/64 (Windows file paths limited in length).
Could you please enable DEBUG logging with logLevel: 'DEBUG' and note what it outputs, and also share any *.log file. It could be an argument is not being correctly formatted when starting the server.
As you note, it is unable to start the underlying Ruby process so we need to get to the bottom of that.
Finally, after #Matthew Fellows answer and after reading his link to https://github.com/pact-foundation/pact-js/issues/64, I moved my project to a shorter path location, simimlar to D:\myproject\, and then the pact mock server was launched and my tests was passed. So until a better solution is discovered I'll work under that short path directory in order to avoid more problems.
Please, read the previous link in order to get more information about this bug because there is very well explained.
Looks to me that the server isn't starting up properly, this is normally because the port is already being used. To see if this is the case, in your node command line (in cmd, type node to go to the node command line), copy/paste the following:
require('http').createServer(function(){}).listen(11108);
The 'listen' function takes in the port number, which I took from your screenshot. Look at what node outputs; my guess is it will show something like this:
Error: listen EADDRINUSE :::11108
at Object.exports._errnoException (util.js:1018:11)
at exports._exceptionWithHostPort (util.js:1041:20)
at Server._listen2 (net.js:1258:14)
at listen (net.js:1294:10)
at Server.listen (net.js:1390:5)
at repl:1:44
at sigintHandlersWrap (vm.js:22:35)
at sigintHandlersWrap (vm.js:73:12)
at ContextifyScript.Script.runInThisContext (vm.js:21:12)
at REPLServer.defaultEval (repl.js:340:29)
This means that there is in fact a port conflict. Look at your task manager and make sure there aren't any instances of node running in the background that might be interfering with your tests spinning up a new server. You might also want to check for any versions of the ruby.exe running; sadly, we have to package the ruby.exe with pact-node, and it spins up a new instance of the mock server using ruby, since that's the language it's written in. From time to time, it does happen that node simply "loses track" of the ruby instance and doesn't shut it off properly.
This is a problem that is well known to us and is something we're actively trying to fix by consolidating all core pact code into a single shared library that can be used across all languages and operating systems without the need to spin up an extra instance. Please bear with us as we get some of these kinks out :)

Resources