I have the following code in one microservices that calls another:
axios.get('http://localhost:4210/usermicroservice/heartbeat')
.then(function(resp) {
console.log('USER HEARTBEAT CALLED ')
})
.catch(function(error) {
console.log('USER HEARTBEAT ERROR ', error)
})
In the called microservice I have the following code:
server.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
next();
})
server.get('/usermicroservice/heartbeat', (req, res) => {
console.log('\n*** USER MICROSERVICE CALLED ***')
res.json({});
})
const PORT = 4210;
server.listen(PORT, () => {
console.log(`hsupp01 UserMicroservice server running on port: ${PORT}`)
})
I get the following error:
{ Error: connect ECONNREFUSED 127.0.0.1:4210
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1097:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 4210,
I am able to accessed the called microservice from Postman using the same url:
http://localhost:4210/usermicroservice/heartbeat
The error message does not capture the problem but the code below had to be executed within an asynchronous block.
axios.get('http://localhost:4210/usermicroservice/heartbeat')
.then(function(resp) {
console.log('USER HEARTBEAT CALLED ')
})
.catch(function(error) {
console.log('USER HEARTBEAT ERROR ', error)
})
Related
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'
}
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.
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: '1234',
server: 'AHMAD\SQLEXPRESS',
database: 'dbms_lab4',
port:1433,
encrypt:false
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from Products', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
I can't connect to SQL Server. When I run the above program and access localhost:5000, nothing appears on the browser but a message on the terminal of vscode:
"The default value for `config.options.enableArithAbort` will change from `false` to `true` in the next major version of `tedious`. Set the value to `true` or `false` explicitly to silence this message. node_modules\mssql\lib\tedious\connection-pool.js:61:23
ConnectionError: Connection is closed.
at Request._query (D:\JS\Sql_Connection\node_modules\mssql\lib\base\request.js:447:37)
at Request._query (D:\JS\Sql_Connection\node_modules\mssql\lib\tedious\request.js:346:11)
at Request.query (D:\JS\Sql_Connection\node_modules\mssql\lib\base\request.js:383:12)
at Immediate.<anonymous> (D:\JS\Sql_Connection\server.js:27:17)
at processImmediate (internal/timers.js:458:21) {
code: 'ECONNCLOSED',
name: 'ConnectionError'
}
ConnectionError: Failed to connect to AHMADSQLEXPRESS:1433 - getaddrinfo ENOTFOUND AHMADSQLEXPRESS
at Connection.<anonymous> (D:\JS\Sql_Connection\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
at Object.onceWrapper (events.js:428:26)
at Connection.emit (events.js:321:20)
at Connection.socketError (D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:12)
at D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at GetAddrInfoReqWrap.callback (D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connector.js:158:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:76:17) {
code: 'ESOCKET',
originalError: ConnectionError: Failed to connect to AHMADSQLEXPRESS:1433 - getaddrinfo ENOTFOUND AHMADSQLEXPRESS
at ConnectionError (D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\errors.js:13:12)
at Connection.socketError (D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:56)
at D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at GetAddrInfoReqWrap.callback (D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connector.js:158:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:76:17) {
message: 'Failed to connect to AHMADSQLEXPRESS:1433 - getaddrinfo ENOTFOUND AHMADSQLEXPRESS',
code: 'ESOCKET'
},
name: 'ConnectionError'
}
ConnectionError: Connection is closed.
at Request._query (D:\JS\Sql_Connection\node_modules\mssql\lib\base\request.js:447:37)
at Request._query (D:\JS\Sql_Connection\node_modules\mssql\lib\tedious\request.js:346:11)
at Request.query (D:\JS\Sql_Connection\node_modules\mssql\lib\base\request.js:383:12)
at D:\JS\Sql_Connection\server.js:27:17
at D:\JS\Sql_Connection\node_modules\mssql\lib\base\connection-pool.js:241:7
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
code: 'ECONNCLOSED',
name: 'ConnectionError'
}"
For SQL Connections: "Microsoft style strings of hostname\instancename are not supported."
EG from : https://www.w3schools.com/nodejs/nodejs_mysql.asp
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
You need to update your config accordingly.
try escaping the \ in the server name
Change
server: 'AHMAD\SQLEXPRESS'
To
server: 'AHMAD\\SQLEXPRESS',
I'm currently writing an mocha test for my project.
The test should cover the output of an ajax request and therefore I created a simple HTTP-Server with node.
This is the current code:
const http = require('http');
const server = http.createServer(function(req, res) {
res.write('test');
});
const port = 5555;
process.on('uncaughtException', function(err) {
console.log("Unhandled Exception, shutting down Server ...")
server.close();
console.log("Server closed!");
console.log(err);
process.exit(1);
});
process.on('SIGTERM', function() {
console.log("Termination called, shutting down Server ...");
server.close();
console.log("Server closed!");
process.exit(1);
});
server.listen('success', function(req, res) {
res.writeHead(200, {
"Content-Type": "application/json"
});
res.write(JSON.stringify({
success: true,
message: "Form success!"
}));
res.close();
});
server.listen('fail', function(req, res) {
res.writeHead(200, {
"Content-Type": "application/json"
});
res.write(JSON.stringify({
success: false,
message: "Form fail!"
}));
res.close();
});
server.listen(port);
console.log("Server running on Port: " + port);
Now for some reason it always throws me an EADDRINUSE error even when the port isn't used. I killed all node/nodejs processes (there weren't any), searched for the program which is using the port (lsof -i tcp:5555) which didn't send any back and even restarted the machine without any difference.
This is the output of the Terminal:
Server running on Port: 5555
Unhandled Exception, shutting down Server ...
Server closed!
{ Error: listen EADDRINUSE success
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at Server._listen2 (net.js:1249:19)
at listen (net.js:1298:10)
at Server.listen (net.js:1382:7)
at Object.<anonymous> (/home/dominik/Documents/workspace/jelly/test/test-server.js:23:8)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
code: 'EADDRINUSE',
errno: 'EADDRINUSE',
syscall: 'listen',
address: 'success',
port: -1 }
npm ERR! Test failed. See above for more details.
I tried to search for solutions already of course, but all I find is kill the server with the same commands. Thanks in advance
You are not using the http module correctly. With the statement server.listen('success',...) you are starting a UNIX socket server on the socket "success" which makes no sense.
Below is an example where the http server returns different responses based in the requested url. I recommend reading this tutorial.
const http = require('http');
const server = http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'application/json',
});
var responseBody = {};
if (req.url === '/success') {
responseBody = {
success: true,
message: "Form success!"
};
}
if (req.url === '/fail') {
responseBody = {
success: false,
message: "Form fail!"
};
}
res.write(JSON.stringify(responseBody));
res.end();
});
const port = 5555;
process.on('uncaughtException', function (err) {
console.log("Unhandled Exception, shutting down Server ...")
server.close();
console.log("Server closed!");
console.log(err);
process.exit(1);
});
process.on('SIGTERM', function () {
console.log("Termination called, shutting down Server ...");
server.close();
console.log("Server closed!");
process.exit(1);
});
server.listen(port, function () {
console.log("Server running on Port: " + port);
});
Test:
curl http://localhost:5555/success
curl http://localhost:5555/fail
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!