Hapijs server start error - Invalid server options - javascript

I am using this simple server program
const Hapi = require('hapi');
const server = new Hapi.Server({
host: 'localhost',
port: 8080,
});
server.route({
path: '/',
method: 'GET',
handler: (request, response) => {
response(true);
},
});
server.start(() => {
console.log('Server running at:', server.info.uri);
});
which gave me the following error on server startup
throw new Error(msgs.join(' ') || 'Unknown error');
^
Error: Invalid server options {
"port" [2]: 8080,
"host" [1]: "localhost"
}
[1] "host" is not allowed
[2] "port" is not allowed
at Object.exports.assert (/Users/aakashverma/Documents/exercises/makeithapi/node_modules/hoek/lib/index.js:736:11)
at Object.exports.apply (/Users/aakashverma/Documents/exercises/makeithapi/node_modules/hapi/lib/schema.js:17:10)
at new module.exports.internals.Server (/Users/aakashverma/Documents/exercises/makeithapi/node_modules/hapi/lib/server.js:32:22)
at Object.<anonymous> (/Users/aakashverma/Documents/exercises/makeithapi/serveEm/serveEm.js:3:16)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
and my package.json has dependencies set this way
"dependencies": {
"axios": "^0.17.1",
"hapi": "^16.6.2"
}
I tried searching for this issue everywhere and found an exact one here but the versions are too old to be compared.
How do I resolve this problem?

The options you're passing need to be passed to a call to server.connection() rather than into the Server constructor.
Snippet from hapi docs:
'use strict';
const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({ port: 3000, host: 'localhost' });
server.start((err) => {
if (err) {
throw err;
}
console.log(`Server running at: ${server.info.uri}`);
});

Could it be typo issue ?
Because in their sample code here they spelled server with lowercase, and you create a new instance while the sample is just using the function.
// Create a server with a host and port
const server = Hapi.server({
host: 'localhost',
port: 8000
});
Update:
Apparently, the current version for hapi is 17, and the question is asked for 16. So, the details of how to configure a server in version 16.6.2 can be found below:
https://hapijs.com/api/16.6.2

Related

how to clear this mongoose error in terminal [duplicate]

I have a problem when I try to connect my app with my database with Mongoose. Already tried following solutions that I found on google:
restarting MongoDB service on windows
manually open db with cmd located on bin file of mongodb
But I can't solve it. Can anyone help me ?
//my connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(db => console.log('DB is connected'))
.catch(err => console.log(err));
And throw's me , this error
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at NativeConnection.Connection.openUri (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\connection.js:797:32)
at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:330:10 at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise ()
at promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:1151:10)
at Mongoose.connect (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:329:20)
at Object. (C:\Users\ivan\Desktop\NodeJS\notes-app\src\db.js:3:10)
at Module._compile (node:internal/modules/cjs/loader:1095:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
I try to put the port on my connection code like this
//my connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(db => console.log('DB is connected'))
.catch(err => console.log(err));
and it throw's me another error
MongooseServerSelectionError: Invalid message size: 1347703880, max allowed: 67108864
at NativeConnection.Connection.openUri (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\connection.js:797:32)
at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:330:10 at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise ()
at promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:1151:10)
at Mongoose.connect (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:329:20)
at Object. (C:\Users\ivan\Desktop\NodeJS\notes-app\src\db.js:3:10)
at Module._compile (node:internal/modules/cjs/loader:1095:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) { 'localhost:3000' => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
If the Error states:
connect() Error :MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
Then the connection to localhost is refused on the IPv6 address ::1 .
Mongoose per default uses IPv6 ..
For a quick check you can set the IPv4 address explicit:
mongoose.connect('mongodb://127.0.0.1/test')
Simply pass third parameter family:4 ie.
mongoose.connect('mongodb://localhost/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true,
family: 4,
})
I finally solved it.
Enabling the IPV6 that MongoDB has disabled by default. Using the following command line on CMD:
mongod --ipv6
And then try again the connection and it works!
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(db => console.log('DB is connected'))
.catch(err => console.log(err));
Posted on behalf of the question asker
const uri = 'mongodb://localhost:27017/test';
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000,
autoIndex: false, // Don't build indexes
maxPoolSize: 10, // Maintain up to 10 socket connections
serverSelectionTimeoutMS: 5000, // Keep trying to send operations for 5 seconds
socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
family: 4 // Use IPv4, skip trying IPv6
}
const connectWithDB = () => {
mongoose.connect(uri, options, (err, db) => {
if (err) console.error(err);
else console.log("database connection")
})
}
connectWithDB()
Probably the hostname/IP of the server to which you want to connect is not correctly set.
I'm used to see that error as:
MongooseServerSelectionError: connect ECONNREFUSED <hostname/hostIP>:<port>
and in the console log you've posted, the <hostname/hostIP> part is malformed/missing.
Example - for a mongodb server running locally on port 27017 this is the error when server is down:
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
If you're using mongodb URI to connect to the db make sure that it looks like this
"mongodb://<hostname/hostIP>:<port>"
Problem is, the localhost alias resolves to IPv6 address ::1 instead of 127.0.0.1
However, net.ipv6 defaults to false.
The best option would be to start the MongoDB with this configuration:
net:
ipv6: true
bindIpAll: true
or
net:
ipv6: true
bindIp: localhost
Then all variants should work:
C:\>mongosh "mongodb://localhost:27017" --quiet --eval "db.getMongo()"
mongodb://localhost:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
C:\>mongosh "mongodb://127.0.0.1:27017" --quiet --eval "db.getMongo()"
mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
C:\>mongosh "mongodb://[::1]:27017" --quiet --eval "db.getMongo()"
mongodb://[::1]:27017/?directConnection=true&appName=mongosh+1.6.0
If you don't run MongoDB as a service then it would be
mongod --bind_ip_all --ipv6 <other options>
NB, I don't like configuration
net:
bindIp: <ip_address>
in my opinion this makes only sense on a computer with multiple network interfaces. Use bindIp: localhost if you need to prevent any connections from remote computer (e.g. while maintenance or when used as backend database for a web-service), otherwise use bindIpAll: true
Open your terminal and type this command: mongod
Then use your app.js to establish a connection by writing this code :
const mongoose=require("mongoose");
mongoose.connect('mongodb://localhost/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true,
family: 4,
})
It's done now. Simply open your mongo shell or your mongodb compass and look for whatever you have added.
I also faced the same problem those commands worked for me(Ubuntu machine)
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chown mongodb:mongodb /tmp/mongodb-27017.sock
Then
sudo service mongod restart

Mongoose throws error ECONNREFUSED on Apollo-Express server

I am sorry if this question is stupid or dumb, please just point me in the right direction, every bit of help is greatly appreciated.
I am currently building a Apollo-Server using express and mongoose. I got the server running with GraphQL, but after connecting it with mongoose, which looks like this:
const express = require("express");
const { ApolloServer, gql } = require("apollo-server-express");
const fs = require("fs");
const port = 4000;
const path = "/graphql";
const app = express();
const typeDefs = gql(fs.readFileSync("./schema.graphql", { encoding: "utf8" }));
const resolvers = require("./resolvers");
const mongo = require('./config');
const { User } = require('./models');
const server = new ApolloServer({
typeDefs,
resolvers,
});
server.applyMiddleware({ app, path });
app.listen(port, () => console.info(`Server started on port ${port}`));
with this as my config:
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const url = 'mongodb://localhost:27017/graphql';
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
};
//mongoose.connect(url, options);
//mongoose.connection.once('open', () => console.log("Connected to mongoDB at ${url}"));
var connectWithRetry = function () {
return mongoose.connect(url, options, function (err) {
if (err) {
console.error(
"Failed to connect to mongo on startup - retrying in 5 sec\n\n",
err
);
setTimeout(connectWithRetry, 5000);
}
mongoose.connection.once("open", () =>
console.log(`Connected to mongo at ${Constants.mongodbUrl}`)
);
});
};
connectWithRetry();
This is supposed to work right?
But when i call npm start server.js i get the following error:
npm start server.js
> start
> node server.js "server.js"
Server started on port 4000
Failed to connect to mongo on startup - retrying in 5 sec MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at NativeConnection.Connection.openUri (/Users/myUsername/newServer/server/node_modules/mongoose/lib/connection.js:832:32)
at /Users/myUsername/newServer/server/node_modules/mongoose/lib/index.js:345:10
at promiseOrCallback (/Users/myUsername/newServer/server/node_modules/mongoose/lib/helpers/promiseOrCallback.js:9:12)
at Mongoose._promiseOrCallback (/Users/myUsername/newServer/server/node_modules/mongoose/lib/index.js:1135:10)
at Mongoose.connect (/Users/myUsername/newServer/server/node_modules/mongoose/lib/index.js:344:20)
at connectWithRetry (/Users/myUsername/newServer/server/config.js:16:19)
at Object.<anonymous> (/Users/myUsername/newServer/server/config.js:30:1)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Module.require (node:internal/modules/cjs/loader:997:19)
at require (node:internal/modules/cjs/helpers:92:18)
at Object.<anonymous> (/Users/myUsername/newServer/server/server.js:14:15)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10) {
reason: TopologyDescription {
type: 'Unknown',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map(1) { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
If you need my installed npm-packages:
graphql-node-server# /path/server
├── apollo-server#2.19.1
├── express#4.17.1
├── graphql#15.4.0
├── mongodb#3.6.3
├── mongoose#5.11.11
└── nodemon#2.0.7
You need to start the MongoDB service before running your code. If it is not running then it will be on a continuous loop trying to reconnect.
Also when it is connected the open event will not be triggered. You need to move it outside of your connection function so it should be like this.
var connectWithRetry = function () {
return mongoose.connect(url, options, function (err) {
if (err) {
console.error(
"Failed to connect to mongo on startup - retrying in 5 sec\n\n",
err
);
setTimeout(connectWithRetry, 5000);
}
});
};
mongoose.connection.once("open", () =>
console.log(`Connected to mongo at ${url}`)
);
connectWithRetry();
My mistake was, that i needed to start the mongoDB process manually. If you did not, start it an rerun it, for me that fixed the issue.
mongod --config /usr/local/etc/mongod.conf --fork

Unable to connect to MSSQL server through Node, while Intellij connection works (MacOS)

I'm running into a strange behaviour where I'm unable to connect to an instance of MSSQL server running locally on docker when using a Node js script, but I can connect to it using Intellij's built-in JDBC connector.
This is the script:
import mysql from "mysql"
const connection = mysql.createConnection({
host : 'localhost',
user : 'sa',
password : 'P#55w0rd!',
database : 'ml_project',
port: 1433,
connectionLimit: 15,
queueLimit: 30,
acquireTimeout: 1000000
});
connection.connect(function(err) {
if ( !err ) {
console.log("Connected to MySQL");
} else if ( err ) {
console.log(err);
}
});
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log(results[0].solution);
connection.end();
});
Which outputs the following error:
Error: Connection lost: The server closed the connection.
at Protocol.end (/Users/IoannouK/ml_project/node_modules/mysql/lib/protocol/Protocol.js:112:13)
at Socket.<anonymous> (/Users/IoannouK/ml_project/node_modules/mysql/lib/Connection.js:94:28)
at Socket.<anonymous> (/Users/IoannouK/ml_project/node_modules/mysql/lib/Connection.js:526:10)
at Socket.emit (events.js:322:22)
at endReadableNT (_stream_readable.js:1187:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
--------------------
at Protocol._enqueue (/Users/IoannouK/ml_project/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/Users/IoannouK/ml_project/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at Connection.connect (/Users/IoannouK/ml_project/node_modules/mysql/lib/Connection.js:116:18)
at Object.<anonymous> (/Users/IoannouK/ml_project/dist/mysql.js:17:12)
at Module._compile (internal/modules/cjs/loader.js:1156:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47 {
fatal: true,
code: 'PROTOCOL_CONNECTION_LOST'
}
/Users/IoannouK/ml_project/dist/mysql.js:27
throw error;
^
And this is the settings panel in my Intellij which works:
I have also tried connecting to a remote database, as well as using a python script, but I received the same results.
const express = require("express");
var sql = require("mssql");
const multer = require("multer");
var config = {
user: "jsudjac",
password: "$#jsuapple",
server: "10.1.4.125",
database: "JSULLC_Test",
};
var dataSource = {
user: "********",
password: "*******",
server: "10.2.2.2",
database: "Stock_Test",
};
const dbconn1 = 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");
}
});

can't get mysql module to work with node js

I am compleeeeetly new to Node js and wanted to start my very first project to get used to it. I am using the excess framework.
I found some nice mysql module which was easily downloaded and installed. The module is correctly placed in the modules folder.
I tried to call it in my app.js file like that:
...
var mysql = require('mysql');
...
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '27sparks&&55',
database : 'react'
});
connection.connect();
app.locals.mysql = connection;
connection.query('SELECT * FROM comment', function(err, rows, fields) {
if (err) throw err;
console.log(rows);
});
connection.end();
When I try to run the www in the /bin directory with this command : node www to start my localhost project I now get following error in the terminal:
/Applications/XAMPP/xamppfiles/htdocs/nodeschool/learn/app.js:79
if (err) throw err;
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at Object.exports._errnoException (util.js:837:11)
at exports._exceptionWithHostPort (util.js:860:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1060:14)
--------------------
at Protocol._enqueue (/Applications/XAMPP/xamppfiles/htdocs/nodeschool/learn/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at Protocol.handshake (/Applications/XAMPP/xamppfiles/htdocs/nodeschool/learn/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/Applications/XAMPP/xamppfiles/htdocs/nodeschool/learn/node_modules/mysql/lib/Connection.js:123:18)
at Object.<anonymous> (/Applications/XAMPP/xamppfiles/htdocs/nodeschool/learn/app.js:75:12)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
Try getting feedback from the connect line (code taken from here) :
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
Also, try setting the port to 3306 manually, even though it defaults to it.
Stupid questions worth asking : is your MySQL instance up and running ? Is it listening on the good port ? Is the password correct ?
you are probably trying to connect to the wrong socket
add a socketPath to your create connection option object like this
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '27sparks&&55',
database : 'react',
socketPath : 'path/to/your/mysqlsocket' // /*example: /var/run/mysqld/mysqld.sock on ubuntu*/
});

NodeJS HTTPS API testing with mocha and super test -"CERT_HAS_EXPIRED"

I need to test an API served via HTTPS with mocha and super test
This is a gist of the server :
...
var app = express();
var _options = {
key: fs.readFileSync('my-key.pem');,
cert: fs.readFileSync('my-cert.pem')
};
// Start HTTPS server
https.createServer(_options, app).listen(app.get('port'), app.get('ip'), function () {
// ok or not logs
});
and this is the route to be tested
app.get('/hello',function (req, res) {
res.json(200);
});
I'm trying to test with this code in test/test.js
var supertest = require('supertest'),
api = supertest('https://localhost:3000');
describe('Hello test', function () {
it('hello', function (done) {
api.get('/hello')
.expect(200)
.end(function (err, res) {
if (err) {
done(err);
} else {
done();
}
});
});
});
but the test FAILs with the following error :
Error: CERT_HAS_EXPIRED
at SecurePair.<anonymous> (tls.js:1349:32)
at SecurePair.EventEmitter.emit (events.js:92:17)
at SecurePair.maybeInitFinished (tls.js:962:10)
at CleartextStream.read [as _read] (tls.js:463:15)
at CleartextStream.Readable.read (_stream_readable.js:320:10)
at EncryptedStream.write [as _write] (tls.js:366:25)
at doWrite (_stream_writable.js:219:10)
at writeOrBuffer (_stream_writable.js:209:5)
at EncryptedStream.Writable.write (_stream_writable.js:180:11)
at write (_stream_readable.js:573:24)
at flow (_stream_readable.js:582:7)
at Socket.pipeOnReadable (_stream_readable.js:614:5)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at emitReadable (_stream_readable.js:404:5)
at readableAddChunk (_stream_readable.js:165:9)
at Socket.Readable.push (_stream_readable.js:127:10)
at TCP.onread (net.js:526:21)
While using plain HTTP the test is PASSING
Have you taken the error message at face value already? Is the certificate you are using to test expired? Is the clock way off on the machine? Also note that TLS certificates are associated with a host name and that host name is generally not "localhost" if you want to do anything useful. Assuming it's not the obvious error of the certificate being expired, try using exactly the correct hostname when connecting to your server.

Categories