Connecting to database error during mocha unit test - node.js

I'm building an app using node.js + express, postgresql for database, and mocha + chai for testing. I am trying to test an API that makes a database query. However, when I run my test I keep getting the error:
{ [Error: ENOENT: no such file or directory, open '.env'] errno: -2, code: 'ENOENT', syscall: 'open', path: '.env' }
Knex:Error Pool2 - error: password authentication failed for user "m11111"
error: Error: Pool was destroyed
Here's my test file:
require('dotenv').load();
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../../app');
var should = chai.should();
var knex = require('../../models/database').knex;
chai.use(chaiHttp);
it('should get all projects', function(done) {
chai.request(server)
.get('/api/projects')
.end(function(err, res){
res.should.have.status(200);
res.should.be.json;
res.body.should.be.a('array');
done();
});
});
My API that i'm testing:
api.get('/api/projects', function(req, res) {
console.log('get projects hit'); //this console logs out
knex('projects').select()
.then(function(data) {
res.send(data);
}).catch(function(error) {
console.log('error: ' + error);
res.sendStatus(200);
});
});
And here's my database connection string:
require('dotenv').load();
module.exports = {
knex: require('knex')({
client: 'pg',
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_USER_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT
},
pool: {
min: 0,
max: 7
},
searchPath: process.env.DB_SEARCHPATH
})
};
Does anyone know what might be wrong?
Thanks in advance!

Related

TypeError: _stream.Readable.from is not a function in sequelize node js

I am getting the below error when I am trying to establish a database connection in my node js application using sequelize
C:\Users\user123\Desktop\project\node_modules\tedious\lib\token\token-stream-parser.js:24
this.parser = _stream.Readable.from(_streamParser.default.parseTokens(message, this.debug, this.options));
^
TypeError: _stream.Readable.from is not a function
I am in initial stage of creating an application. Where I have just tried to create a database connection, for which I have created three files
index.js
var dotenv = require("dotenv").config().parsed;
var customEnv = require("custom-env");
customEnv.env("development").env();
var express = require("express");
const helmet = require("helmet");
var cookieParser = require("cookie-parser");
const app = express();
app.use(helmet());
app.use(cookieParser());
require("./db.js");
httpserver = require("http").createServer(app);
httpserver.timeout = 0;
httpserver.listen(3457, async () => {
connectedEmitter.on("connectedDbs", () => {
console.log(` ----- SERVER LISTENING ON PORT `);
});
});
db.js
const Sequelize = require('sequelize');
const eventEmitter = require('events');
global.connectedEmitter = new eventEmitter()
global.sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
host: process.env.DB_HOST,
port: 1433,
dialect: process.env.DB_DIALECT,
ssl: false,
dialectOptions: {
ssl:false
},
logging:false,
pool: {
max: 20,
min: 0,
idle: 30000
}
});
sequelize.authenticate().then(() => {
console.log(`${process.env.DB_NAME} - Connection has been established successfully.`);
global.connectedEmitter.emit('connectedDbs')
}).catch((err) => {
console.error(' - Unable to connect to the database:', err);
});
.env (I am giving dummy credentials as I cannot provide original credentials)
# ################################## Database Credentials ##############################################
DB_NAME=mydb
DB_USER=username
DB_PASS=password
DB_HOST=hostname
DB_DIALECT=mssql
Can anyone please tell me why am I getting the error mentioned. Where have I made the mistake in setting the database connection. Please help.
I also faced this issue. Turns out tedious had issues with node versions below 12, and my production app service was running on node 10.
GitHub link that mentions this

can't connect on minio with node js

i tried to connect on minio with node js using minioClient
this is my code
Minio.js
const Minio = require('minio')
const minioClient = new Minio.Client({
endPoint: 'xxxxxx',
port: 9000,
useSSL: true,
accessKey: 'xxxxxx',
secretKey: 'xxxx'
});
module.exports = minioClient
fileupload.js
const minioClient = require('../config/connection/Minio')
module.exports = minioUpload = {
upload: async(req, res) => {
if (req.file) {
var metaData = {
'Content-Type': 'application/octet-stream',
'X-Amz-Meta-Testing': 1234,
'example': 5678
}
var originalname = req.file.originalname.split(' ');
const fileName = originalname.join('_');
try {
// Using fPutObject API upload your file to the bucket maztou.
minioClient.putObject('maztou', fileName, req.file.buffer, metaData, function(err, etag) {
if (err) return console.log(err)
return res.status(201).json('File uploaded successfully.', fileName)
});
} catch (err) {
console.log(err, '<== ERROR');
}
}
}
}
router.js
const express = require('express')
const minioUpload = require('../controllers/fileupload')
const router = express.Router()
const multer = require('multer')
router.route('/uploads').post(multer({ storage: multer.memoryStorage() }).single("file"), minioUpload.upload)
module.exports = router
And the server return this :
Error: connect ETIMEDOUT XXXX:9000
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
errno: -60,
code: 'ETIMEDOUT',
syscall: 'connect',
address: 'XXXX',
port: 9000
}
Can some one help me for this issus, i'have already read all the documentation about minioClient , all my setup is good, and i have. this issus !
The timeout indicates that the client cannot connect to the server. You should check if the endpoint, port and credentials passed to MinIO client are correct and turn off useSSL if TLS is not enabled. If your MinIO server is running in docker, you may want to check if the port is exposed.

NodeMailer through error connect ECONNREFUSED 127.0.0.1:465

I try many solutions but none of them work. I will use this to send mail to everyone through custom domain mail who are login using my app
I have used the following js code in index.js to integrate app and adapter
const express = require( 'express' );
const app = express();
const port = 5000;
const nodemailer = require( 'nodemailer' );
let transporter = nodemailer.createTransport( {
service: 'smtp.CustomDomain.mail',
port: 465,
secure: false,
auth: {
user: 'XYC#CustomDomain.com',
pass:'123'
}
} )
let message = {
from: "XYC#CustomDomain.com",
to: "XYZ#gmail.com",
subject: "Message title",
text: "Plaintext version of the message",
html: "<p>HTML version of the message</p>"
};
app.get( '/', (req,res) =>
{
transporter.sendMail( message, (error,info) =>
{
if ( error ){
console.log("Something went wrong",error)
}
if ( info )
{
console.log("Mail send successfully")
}
})
} )
app.listen( port, () =>
{
console.log("Server is running on port "+port)
})
Here is the error message
Server is running on port 5000
Something went wrong Error: connect ECONNREFUSED 127.0.0.1:465
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
errno: -4078,
code: 'ESOCKET',
syscall: 'connect',
address: '127.0.0.1',
port: 465,
command: 'CONN'
}

Heroku error: "connect ECONNREFUSED 127.0.0.1:3306" when trying to deploy Express + React application

I was trying to deploy my Express + React application to Heroku. Heroku connected successfully with my Github account, then clicking "Deploy Branch" led to "Your app was successfully deployed". But when I went to view my website, it showed:
"Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details".
Here are my logs:
Starting process with command `npm start`
> myproject# start /app
> node backend/index.js
My project SQL server listening on PORT 4000
/app/backend/index.js:22
if (err) throw err;
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
And the index.js which connects to MySQL:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /my-project to see my project')
});
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'myjs123#',
database: 'my-project',
debug: false
});
pool.getConnection((err, connection) => {
if (err) throw err;
app.get('/my-project', (req, res) => {
connection.query(SELECT_ALL_FACTS_QUERY, (err, results) => {
if (err) {
return res.send(err)
}
else {
return res.json({
data: results
})
};
});
});
});
const SELECT_ALL_FACTS_QUERY = 'SELECT * FROM `my-project`.`my-table`;';
app.listen(4000, () => {
console.log('My project SQL server listening on PORT 4000');
});
What did I do wrong and how could I deploy it?
I think in the below code the localhost should not be used, the localhost will not work in deployment.
const pool = mysql.createPool({
connectionLimit: 10,
//here
host: 'localhost',
user: 'root',
password: 'myjs123#',
database: 'my-project',
debug: false
});
And another mistake I found is you should use an environment variable to store
port numbers. In production, the port number is assigned by Heroku, if not assigned you
can assign. So your code should be
let port=process.env.PORT||4000
app.listen(port, () => {
console.log(`App running on port ${port} `);
});
you need to add (add-ons) to your heroku account
and connect it to your app.
For example, you can use (JAWS_DB mysql)
By having the following code in your connection:
// import the Sequelize constructor from the library
const Sequelize = require('sequelize');
require('dotenv').config();
let sequelize;
// when deployed on Heroku
if (process.env.JAWSDB_URL) {
sequelize = new Sequelize(process.env.JAWSDB_URL);
} else {
// localhost
sequelize = new Sequelize(process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD, {
host: 'localhost',
dialect: 'mysql',
port: 3306
});
}
module.exports = sequelize;
It passed this stage after I removed if (err) throw err;, still not sure why this happened.
Nithin's answer was taken into account too.
the same errorhappened to me while i was trying to connect to heroku cli and i jus read the heroku config for proxy and that was the case. problem solved by configuring the http and https proxy like
set HTTP_PROXY=http://proxy.server.com:portnumber
or set HTTPS_PROXY=https://proxy.server.com:portnumber

problem about connecting to my Postgres with node.js through knex

I am facing this problem with connecting to my Postgres with node.js through knex. I am trying this for the first time and I ask humbly to help me solving the issue. please help me.
My code is the following. Every time I make a request, PostgreSQL doesn't connect so nothing happens.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex')
const db = knex({
client: 'pg',
connection: {
host: '127.0.0.1',
user: 'postgres',
password: '',
database: 'smart-brain'
}
});
db.select('*').from('users').then(console.log).catch(console.log);
app.use(cors());
app.post('/signin', (req, res) => {
if (req.body.email === database.users[0].email &&
req.body.password === database.users[0].password) {
res.json('success');
} else {
res.status(400).json('error logging in');
}
})
app.post('/register', (req, res) => {
const {
name,
email,
password
} = req.body;
db('users')
.returning('*')
.insert({
email: email,
name: name,
joined: new Date()
})
.then(respons => {
res.json(response);
}).
catch(err => res.status(400).json('unable to register'))
})
app.listen(3000, () => {
console.log('app is running on the port 3000');
});
and the response is these on npm
Error: connect ECONNREFUSED 127.0 .0 .1: 5432
at TCPConnectWrap.afterConnect[as oncomplete](net.js: 1141: 16) {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 5432
}
If you are in Ubuntu, then go to the following folder.
/etc/postgresql/{your_pg_version}/main
Or If you are in Windows, then go to the following folder,
C:\Program Files\PostgreSQL\{your_pg_version}\data\
Open the file pg_hba.conf to write with SuperUser/Administrative permission,
Go to the bottom, and put trust at the end of following lines.
# Database administrative login by Unix domain socket
local all postgres trust
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
After that, restart your PostgreSQL server and try again with your code.

Resources