In my app.js file, I have the following code
var express = require('express');
var app = express();
var port = 8080;
var util = require('util');
var router = require('./base/js/routes.js');
//==================================================================
app.use('/', router);
// start the server
app.listen(port, function(request, response) {
console.log('Port 8080: Server Begins');
});
//==================================================================
var ipaddress = '123.456.789';
//==================================================================
var mongoose = require('mongoose');
var mongoURI = "mongodb://"+ ipaddress +":27017/test";
var MongoDB = mongoose.connect(mongoURI);
MongoDB.on('error', function(err) {
console.log(err.message);
});
MongoDB.once('open', function() {
console.log("mongodb connection open");
});
//==================================================================
The line var MongoDB = mongoose.connect(mongoURI);
is causing nodeJS not to work. I do not know why. NodeJS is on port 8080 and MongoDB is on port 27017.
I am fairly certain I installed mongodb package (and opened the port correctly). I just do not understand why nodeJS doesnt work when i include that connection line.
Side Note: Also I have the package forever installed: forever start -c nodemon app.js for nodeJS. If that is any relevance.
You are using wrong IP address format.
First try to connect with your local mongoDB instance if it work then you to check the IP address your trying to connect is correct or not.
Add the correct error message if problem still remain same.
change your mongod.conf file from /etc folder
In mongod.conf you need to change bindIp
If connection is local then set bindIp as
bindIp = 127.0.0.1
and if you want to use remote database then change bindIp as
bindIp = 0.0.0.0
then restart mongo service
hope this helps...
Related
I am writing a RESTful API. IT runs on node.js using the express.js framework, mongodb using mongoose as the object modelling tool & body-parser to pass the http. Everytime I start the server & navigate to the specified IP address, I get a "CANNOT GET/" error. How can I can around this? Some advice would be much appreciated .
I have tired using a different port number but the problem still persists.
Here is a copy of my server.js code:
var express = require('express'),
app = express(),
IP = process.env.IP,
port = process.env.PORT || 8080 ,
mongoose = require('mongoose'),
tasks = require('./api/models/todosModel'),
bodyParser = require('body-parser');
//handiling of promise
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Todosdb',{ useNewUrlParser: true });
app.use(bodyParser.urlencoded({extended:true})); // telling the sever instance to use body parser
app.use(bodyParser.json());
var Routes = require('./api/routes/todoRoutes');
//passing the server instance to the routes
Routes(app);
app.listen(port,IP);
console.log("The TODO API server is running on IP: " + IP + " and port: " + port);
The todoRoute code :
'use strict';
module.exports = function(app){
var todofunctions = require('../controllers/todoController');
// todo routes
app.route('/tasks') //task [GET (all the tasks),POST]
.get(todofunctions.listTasks)
.post(todofunctions.createTask);
app.route('/tasks/:taskId') //a task [GET(single task),PUT,DELETE]
.put(todofunctions.updatetask)
.get(todofunctions.readTask)
.delete(todofunctions.deleteTask);
};
It's probably because you have not defined any handler for /.
Try going to the /tasks instead in your browser, then you will get some response.
Trying to test an endpoint in express But keep getting 404 error.
var express = require("express")
var app = express()
//var http = require('http').Server(app)
app.get('/', function(req,res){
res.send('ok from end point')
})
var port = process.env.PORT|| 8080
var localhost = 'someLocalHost.med.gov'
console.log({'localhost':localhost,
'post':port})
//
app.listen(port,localhost,function(err){
if (err){
console.log('err')
}
else {
console.log('Listening')
}
})
When I go to
http://someLocalHost.med.gov:8080/
I get a 404 error
Localhost refers to 127.0.0.1. You can't just launch a server on any address that you want. If you're wanting to override localhost you can look into modifying your HOSTS file locally to setup an alias for localhost.
So I ended up http:// IP_ADDRESS:8080 and that took care of it.
I am trying to run a node js app on Heroku using WebSockets. However, I am not able to resolve this error (As seen in conosle of Chrome browser)
WebSocket connection to 'wss://myappname.herokuapp.com:27225/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I am using 'wss' since Heroku runs on HTTPS.
My client side code is :
$.get("https://myappname.herokuapp.com/port",function(data){
port = data;
console.log(data);
host = 'wss://myappname.herokuapp.com:' + port + '/';
ws = new WebSocket(host);
});
My server side code is :
var WebSocketServer = require("ws").Server
var fs = require('fs');
var express = require('express');
var app = express();
var http = require('http');
var port = process.env.PORT || 5000;
var request = require('request');
var server = http.createServer(app);
var serverOnPort = server.listen(port);
console.log("Server listening on port ",port);
var wss = new WebSocketServer({server: serverOnPort});
console.log("websocket server created");
Any help would be appreciated.
Thank You.
So it seems like I was trying to over-do it with the port number. Just using the host as wss://myappname.herokuapp.com/ works well.
I also found this problem. It seems Heroku will automatically route port number. It does's allow to specify port number in url. In my chrome, it show ERR_CONNECTION_RESET. This also happen with XMLHttpRequest. Port number still need when you test with localhost or another server which is not Heroku.
I'm very new for this stuff, and trying to make some express app
var express = require('express');
var app = express();
app.listen(3000, function(err) {
if(err){
console.log(err);
} else {
console.log("listen:3000");
}
});
//something useful
app.get('*', function(req, res) {
res.status(200).send('ok')
});
When I start the server with the command:
node server.js
everything goes fine.
I see on the console
listen:3000
and when I try
curl http://localhost:3000
I see 'ok'.
When I try
telnet localhost
I see
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'
but when I try
netstat -na | grep :3000
I see
tcp 0 0 0.0.0.0:3000 0.0.0.0:* LISTEN
The question is: why does it listen all interfaces instead of only localhost?
The OS is linux mint 17 without any whistles.
If you don't specify host while calling app.listen, server will run on all interfaces available i.e on 0.0.0.0
You can bind the IP address using the following code
app.listen(3000, '127.0.0.1');
If you want to run server in all interface use the following code
app.listen(3000, '0.0.0.0');
or
app.listen(3000)
From the documentation: app.listen(port, [hostname], [backlog], [callback])
Binds and listens for connections on the specified host and port. This method is identical to Node’s http.Server.listen().
var express = require('express');
var app = express();
app.listen(3000, '0.0.0.0');
document: app.listen([port[, host[, backlog]]][, callback])
example:
const express = require('express');
const app = express();
app.listen('9000','0.0.0.0',()=>{
console.log("server is listening on 9000 port");
})
Note: 0.0.0.0 to be given as host in order to access from outside interface
I currently have Google cloud Compute engine running nodejs that is connected to a Google Cloud SQL witch takes data from MySQL workbench. This is my server.js file that I run with 'node'
var gcloud = require("gcloud");
var express = require("express");
var http = require('http');
var mysql = require("mysql");
var connection = mysql.createConnection({
port: "3306",
host : "173.194.87.72",
user : "root",
password : "****",
database : "scripto_5_k"
});
var app = express();
/* Connection to Database */
connection.connect(function(error){
if(error)
{
console.log("Problem with MySQL "+error);
}
else
{
console.log("Connected with Database ");
}
});
app.set('port', process.env.PORT || 3000);
app.get('/',function(req,res){
res.send('hello index');
});
app.get('/load',function(req,res){
console.log("/load hit");
connection.query("SELECT * from user",function(err,rows){
if(err)
{
console.log("Problem with MySQL"+err);
}
else
{
res.end(JSON.stringify(rows));
}
});
});
/*start the server */
app.listen(3000,function(){
console.log("its started on PORT %s", app.settings.port);
});
this should take all the data in the user table and put it to JSON when I use /load. But I cant get Postman to display the data. This is the address I have been using
http://130.211.90.249:3000/load
The address is from Google cloud the port is the one I set in the server.js file and /load should use the function I have written above.
Why am I not seeing a result with this input? I am running the server with 'node server.js' on my VM instance and it says I have successfully connected.
Any help is really appreciated.
Edit 1
This is what my VM looks like when I run the server.js
my_user_name#nodejs-2:~$ node server.js
its started on PORT 3000
Connected with Database
No error but in Postman I get "Could not get any response" when I put in the address given above.
Edit 2
Do I need to create a http server in the server.js file that I run so that the JSON object can be reached by the request in Postman?
Edit 3
If I follow the ip address of my google cloud VM it takes me to a default page for Bitnami but tells me that node js is running in the cloud. Do I need to remove this default page or is it fine to just leave whilst the server runs?
Here is a link http://130.211.90.249/
Since the app is listening on port 3000 in your code, you need to create a firewall rule to make that port available from the outside.
From the developer console for that project, go to Networks and view the details for the default network. Create a rule to allow traffic on port 3000.