Mongoose.connect not working - javascript

When I run node server.js in the command line I get this error:
C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms>node server.js
C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms\node_modules\express\lib\router\index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a Object
at Function.use (C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms\node_modules\express\lib\router\index.js:458:13)
at Function.<anonymous> (C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms\node_modules\express\lib\application.js:220:21)
at Array.forEach (<anonymous>)
at Function.use (C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms\node_modules\express\lib\application.js:217:7)
at Object.<anonymous> (C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms\server.js:34:5)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
I think part of it might be that the mongoose.connect is an unresolved function. Does anyone know how to fix this error?
This is my code:
// Get dependencies
var express = require('express');
var path = require('path');
var http = require('http');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
// import the routing file to handle the default (index) route
var index = require('./server/routes/app');
const messageRoutes = require('./server/routes/messages');
const contactRoutes = require('./server/routes/contacts');
const documentRoutes = require('./server/routes/documents');
// establish a connection to the mongo database
mongoose.connect('mongodb://localhost:27017/cms');
var app = express(); // create an instance of express
// Tell express to use the following parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(logger('dev')); // Tell express to use the Morgan logger
// Tell express to use the specified director as the
// root directory for your web site
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/', index);
app.use('/messages', messageRoutes);
app.use('/contacts', contactRoutes);
app.use('/documents', documentRoutes);
// Define the port address and tell express to use this port
const port = process.env.PORT || '3000';
app.set('port', port);
// Create HTTP server.
const server = http.createServer(app);
// Tell the server to start listening on the provided port
server.listen(port, function() {console.log("API running on localhost: " +
port)});

Your mongoose.connect call is working fine. If it wasn't then you would definitely have received a PromiseRejection for connection failure and a deprecated warning for UnhandledPromiseRejection.
Still you can ensure that by adding few event listeners on mongoose events.
mongoose.connect('mongodb://127.0.0.1:27017');
mongoose.connection.on('connected', () => console.log('Connected'));
mongoose.connection.on('error', () => console.log('Connection failed with - ',err));
Coming to your error. This is more likely to happen when you have passed anything but a function as your handler to your app.use or router.use call. app.use and router.use both require functions to be passed to them which later express would call whenever a request arrives.
The import statements on top of your code, where you require your routers are most likely to be the culprits here as by default every module.exports is an object.
I need to look into your router files to further dig into the problem, but you may yourself verify the same. Just see if the module.exports of every router file imported points to a express router instance - express.Router(). This way every route file will export a configured express.Router() instance which will be a function attached to app via app.use() call.

Replace mongodb://localhost:27017 with mongodb://127.0.0.1:27017
To capture the exact error please follow the below approach.
const mongoose = require('mongoose');
const url = "mongodb://127.0.0.1:27017";
mongoose.connect(url).then(() => {
console.log("Connected to Database");
}).catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});

Related

having problem in in using node.js for a socket.io

io.on('connection', socket =>{
^
TypeError: io.on is not a function
at Object. (D:\shalini course\projects\chat app\nodeserver\nodeapp.js:7:4)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Module._load (node:internal/modules/cjs/loader:922:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
it shows this error when I run a cmd - node nodeapp.js
please do reply If any idea how to fix it?
enter image description here
I tried running an application of socket.io on 5000 port using node.js but it's not working.
you have to add the socket io server to the http server, the mistake you are doing is that you are adding the socket io server to nowhere, to the aire, try with this before to iniltialize the server on port 5000
//CREATE THE SERVER NODE JS
const server = http.createServer(app)
// CREATE SOCKET.IO SERVER CONNECT WITH OUR SERVER
const io = new Server(server);
HERE PUT YOUR SOCKET IO CODE, io.on,.....
server.listen(port,()=>{
console.log(`listening on port ${port}`)
});
Yes, "io" that you are trying to use a method on is not a function on that class
in your code "io" includes the whole package of socketio all the classes and functions
"io" in your code has all the classes that your can use by
const myClass = new io.(someclass)()
You can impove your code like this
const socketiopackage = require('socket.io')
const port = 5000
const io = new socketiopackage.Server(5000,{cors: {"Access-Control-Allow-Origin": "*",methods: ["GET", "POST", "OPTIONS"]},})
var users = {}
io.on('connection',socket=>{
socket.on('new-user-joined',name=>{
users[socket.id]=name
socket.broadcast.emit('user-joined',name)
})
socket.on('send',message=>{
socket.broadcast.emit('recieve',{message,name:user[socket.id]})
})
})
or it is easier to directly import your required class
const { Server } = require('socket.io')
const port = 5000
const io = new Server(5000,{cors: {"Access-Control-Allow-Origin": "*",methods: ["GET", "POST", "OPTIONS"]},})
var users = {}
io.on('connection',socket=>{
socket.on('new-user-joined',name=>{
users[socket.id]=name
socket.broadcast.emit('user-joined',name)
})
socket.on('send',message=>{
socket.broadcast.emit('recieve',{message,name:user[socket.id]})
})
})
I have added some cors settings in the options for creating a server, it is a good practice to do so
Using Nodemon
install it using
npm install -g nodemon
then use it using
nodemon (fileName).js

Incomplete response received from application on Node Js Project

I have tried to install the NPM packages from the cpanel. But when I try to open the website, I get the response incomplete response received from application. When i run it offline, it works properly, but when i move it to the cpanel, it gives me the incomplete response error
var express = require("express"),
app = express(),
mongoose = require("mongoose"),
flash = require("connect-flash"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
session = require("express-session"),
methodOverride = require("method-override"),
nodemailer = require("nodemailer"),
multer = require("multer"),
dotenv = require("dotenv").config(),
Product = require("./models/products"),
User = require("./models/user");
var mongoDB = process.env.MONGODB_URL;
mongoose.connect(mongoDB, { useNewUrlParser: true , useUnifiedTopology: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
var indexRoutes = require("./routes/index"),
storeRoutes = require("./routes/products");
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(methodOverride("_method"));
app.use(flash());
//User Passport Config
app.use(require("express-session")({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function(req, res, next){
res.locals.currentUser = req.user;
res.locals.error = req.flash("error");
res.locals.success = req.flash("success");
next();
});
app.use(indexRoutes);
app.use("/store", storeRoutes);
app.use(function(req, res){
res.send ("Error finding page")
})
const port = process.env.PORT;
app.listen (port, function(){
console.log ("Server Active");
});
this is what i saw in the the .htaccess file. I only placed some passwords and other private info in the .env file
# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php70” package as the default “PHP” programming language.
<IfModule mime_module>
AddHandler application/x-httpd-ea-php70 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit
# DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN
PassengerAppRoot "/home/zenitcou/zenitcouture"
PassengerBaseURI "/"
PassengerNodejs "/home/zenitcou/nodevenv/zenitcouture/11/bin/node"
PassengerAppType node
PassengerStartupFile app.js
# DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END
# DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION BEGIN
<IfModule Litespeed>
</IfModule>
# DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION END
Share the response you are getting, that we can help you better
From the configuration provided, I can't tell the exact cause but I may have enough experience why you end up getting "incomplete response received from the application".
The error message might be confusing, but what it really wants to say is, nothing is actually sent from your app upon HTTP request is sent by the proxy aka. Phusion Passenger.
You can read more about what are those Passenger config in their docs
but my gist is one of these:
Your app is maybe crashed due to improper configuration. I suggest using PassengerAppEnv development to track error messages.
Phusion passenger integration on Node.JS is somewhat magic, they just don't care what app.listen port you're giving on. But it probably crashes because you set them undefined. Please set a fallback on your PORT env like const port = process.env.PORT || 80;
You set PassengerStartupFile as app.js. Is it true? (People usually set their main entry file as server.js. You have to make sure the file exists.
I faced the same error.
For me, it was log4js. The process.send() function was undefined.
By disabling the clustering of log4js, all become fine.
To find where the error is, I proceeded with code reduction. Compiling a few lines of codes
May it helps someone

Error occured while trying to proxy to: localhost:4200/api/v1/generate_uid

I am following a tutorial (https://levelup.gitconnected.com/simple-application-with-angular-6-node-js-express-2873304fff0f) on creating an app with Angula CLI, Node.js and Express. I use a proxy to start the app, the file defining the proxy looks like this:
{
"/api/*": {
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
The command I use to start the app is this one:
ng serve --proxy-config proxy.conf.json
The tutorial said that:
All requests made to /api/... from within our application will be forwarded to http://localhost:3000/api/...
To be honest, I don't really know how it is supposed to work, because when I launch the app, I still use the URL: http://localhost:4200/ .
But I didn't have a problem until now. I just created a route with Express.js at the Endpoint /api/v1/generate_uid .
But the problem is when I go to http://localhost:4200/api/v1/generate_uid it shows this message:
Error occured while trying to proxy to: localhost:4200/api/v1/generate_uid .
The following is the message I get in the console:
[HPM] Error occurred while trying to proxy request /api/v1/generate_uid from localhost:4200 to http://localhost:3000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)
And when I go to http://localhost:3000 it always says that the connection has failed.
For further references, Here are the app.js of my express API and generate_uid.js which defines the route:
app.js
var express = require('express');
var uid = require('uid-safe');
var router = express.Router();
router.get('/', function(req, res, next) {
var strUid = uid.sync(18);
res.json({guid: strUid});
});
module.exports = router;
generate_uid.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var users = require('./routes/users');
var generate_uid = require('./routes/generate_uid');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser())
app.use('/api/v1/users', users);
app.use('/api/v1/generate_uid', generate_uid);
module.exports = app;
So I really don't know what the solution is. Thanks in advance for your answers !!
As said in the comments, it looks like the app doesn't have the .listen() function, which is very important to bind to the port.
app.listen(3000, () => {
console.log("Server started in port 3000!");
});

Getting a " Cannot GET /" when attempting to retrieve a json object from a node server

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.

typeError when passing in objects to require() for passport

I get typeError: object is not a function
when I run:
node server.js
for the following line of code
require('./app/routes.js')(app, passport);
from the following code for my server.js file:
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./config/database.js');
// configuration ================================================================
mongoose.connect(configDB.url); // connect to our database
// require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // get info from html forms
app.use(bodyParser.urlencoded({ extended: true}));
app.set('view engine', 'ejs'); // set up ejs for templating
// requirements for passport:
app.use(session({ secret: 'ilovescotchscotchyscotchscotch'}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ========================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
// launch =======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
not entirely sure why this is happening...
I was following this tutorial btw: https://scotch.io/tutorials/easy-node-authentication-setup-and-local
Thanks!
Based on your comments: this post does a pretty good job of explaining how require works in nodeJS (it's not a Javascript thing). Basically every file that can be required is generally expected to export something that the requiring file can assign to a variable (e.g. var someVar = require('someFile');). IF the exported value is a function then you can immediately invoke it before assigning to that variable (e.g. var someVar = require('someFile')(params);). For your error it appears that the file ./app/routes.js is not exporting a function.
FILE: ./app/routes.js
// some code that does cool stuff
// ...
// Time to expose whatever we want to the requiring file
module.exports = someObject; // Or value, function, etc.
FILE: main.js
// we want cool stuff from routes.js
var coolStuff = require('./app/routes.js');
// someObject from ./app/routes.js is now assigned to coolStuff
coolStuff(); // ERROR: object is not a function
console.log(typeof coolStuff) // "object"

Categories