Recently i ordered a VPS debian 9 cloud and wanted to put a small test project on there made in nodeJS, on a local pc it works fine but when i transfer it over and try to run it it gives me this error.
module.js:557
throw err;
^Error: Cannot find module './models/info'
at Function.Module._resolveFilename (module.js:555:15)
at Function.Module._load (module.js:482:25)
at Module.require (module.js:604:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/root/Server_files/index.js:5:14)
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)
at startup (bootstrap_node.js:193:16)
at bootstrap_node.js:617:3
the code that gives errors when run on the cloud is this one below.
const express = require('express');
const path = require('path');
const Broutes = require('./routes/Broutes');
const mongoose = require('mongoose');
const Info = require('./models/info');
const BodyParser = require('body-parser');
const app = express();
mongoose.connect("###");
var db = mongoose.connection;
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(BodyParser.urlencoded({ extended: false}));
app.use('/', Broutes);
app.post('/Info/add', (req,res)=>{
let info = new Info();
info.Name = req.body.Name;
info.Address = req.body.Address;
info.Email = req.body.Email;
info.save((err,info)=>{
if (err){
console.log(err);
} else{
res.redirect('/');
}
})
})
app.listen(3000, (req, res)=>{
console.log('server started on port 3000');
})
as i already said this code works just fine on a local computer but when on the VPS it starts spitting out this error.
Thats probably because you are missing a file/module.
In this line:
const Info = require('./models/info');
You have required an info.js file which is in the models folder in your root directory, but according to nodejs, that file doesn't exist. Just confirm that it's there and your code will run as normal.
Related
throw new MongooseError('The uri parameter to openUri() must be
a ' +
^
MongooseError: The uri parameter to openUri() must be a string,
got "undefined". Make sur
first parameter to mongoose.connect() or mongoose.createConnection() is a string.
at NativeConnection.Connection.openUri (C:\Users\niko\Desktop\opaa\node_modules\mongoose\nnection.js:694:11)
at _mongoose._promiseOrCallback.cb (C:\Users\niko\Desktop\opaa\node_modules\mongoose\lib\js:351:10)
at promiseOrCallback (C:\Users\niko\Desktop\opaa\node_modules\mongoose\lib\helpers\promislback.js:10:12)
at Mongoose._promiseOrCallback (C:\Users\niko\Desktop\opaa\node_modules\mongoose\lib\inde at
Mongoose.connect
(C:\Users\niko\Desktop\opaa\node_modules\mongoose\lib\index.js:350:20)
at Object. (C:\Users\niko\Desktop\opaa\app.js:9:10)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
const { response } = require('express');
const express = require('express');
const path = require('path');
const dotenv = require('dotenv')
const mongoose = require('mongoose');
dotenv.config();
mongoose.connect( process.env.DB_CONNECT, { useNewUrlParser: true }, () =>{
console.log("connected to db");
});
const route = require('./routers/routers');
const { connect } = require('./routers/routers');
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.set("views", "views")
app.set("view engine", "hbs")
app.use(express.static('public'));
app.use('/user', route);
app.listen(3000, () => console.log("Server Is Runing on localhost:3000"));
You may try to be sure you've passed the DB_CONNECT.
you may try DB_CONNECT=YOUR_DB_URI node index.js
also, you may check with console.log(process.env.DB_CONNECT) at the beginning of your script.
The error message tells that the mongoose.connect received URL is undefined. I suggest you instead process.env.DB_CONNECT try passing an URL to the DB for testing purpose see if that works.
The issue is with the process.env.DB_CONNECT is not setting up correctly, you might need to check dotenv configuration.
I am still relatively new to NodeJS. Now I encounter this problem: I had a file called "./models/route" I renamed it by changing the filename in VS Code to: "./models/routes". I then changed that name in all of the scripts. I checked, doubledchecked, triplechecked and quadruplechecked that it has been changed everywhere and it has.
Now I get this error in the console:
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module './models/routes'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\node-projects\wandelverhalen\controllers\routesController.js:4:16)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\node-projects\wandelverhalen\index.js:11:26)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
[nodemon] app crashed - waiting for file changes before starting..
The error apparently is encountered in internal/modules/cjs/loader.js:638. So it does not point me to a script that I made or can change.
I really am at a loss...
Edit:
As Mosifa points out in his comment the error points to ./wandelverhalen/controllers/routesController.js and ./wandelverhalen/index.js.
Here are the scripts. I still can't find the problem.
index.js:
"use strict";
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const Routes = require("./models/routes");
const homeController = require("./controllers/homeController");
// const errorController = require("./controllers/errorController");
const routesController = require("./controllers/routesController");
mongoose.connect("mongodb://localhost:27017/db_wandelen", {
useNewUrlParser: true
});
const db = mongoose.connection;
db.once("open", () => {
console.log("Connected to MongoDB");
});
app
.set("port", process.env.PORT || 3000)
.set("view engine", "ejs")
.use(
express.urlencoded({
extended: false
})
)
.use(express.json())
.use(express.static("static"))
.use(layouts)
.use((req, res, next) => {
console.log(`Request made to ${req.url}`);
next();
})
// .use(errorController.pageNotFoundError)
// .use(errorController.internalServerError)
.get("/", homeController.start)
.get("/kempen", homeController.kempen)
.get("/rivieren", homeController.rivieren)
.get("/oost_belgie", homeController.oost_belgie)
.listen(app.get("port"), () => {
console.log(`Server running at port ${app.get("port")}`);
});
routesController.js:
"use strict";
const mongoose = require("mongoose");
const Routes = require("./models/routes");
exports.getAllRoutes = (req, res, next) => {
Routes.find({}, (error, routes) => {
if (error) next(error);
req.data = routes;
next();
});
};
This question already has answers here:
NodeJs : TypeError: require(...) is not a function
(8 answers)
Closed 6 years ago.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use('/', require('../routes')(express));
exports.server = app.listen(port, () => {
console.log('Server active on', port);
});
Am I missing a npm package?
Error
TypeError: require(...) is not a function
at Object.<anonymous> (C:\xampp\htdocs\url-shortener\src\server.js:12:34
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)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:418:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:533:3
Your ../routes source file is not exporting a function.
Try replacing this line:
app.use('/', require('../routes')(express));
with:
console.log( require('../routes') );
I bet it prints an object ({ ... }) rather than a function.
Inside your ../routes file you need to explicitly export the important function:
module.exports = importantFunction;
function importantFunction(string) {
console.log(string);
}
Now you scripts which import it can call it.
require('../routes')("hi") // should log "hi"
I'm new to node.js. I was trying to run the code from the link https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens. When I tried to run the server.js. The following error was coming:
E:\Eclipse IDE\Enide-Studio-2014.17-luna-SR1-win64-20141011\Enide-Studio-2014.17-luna-SR1-win64\ws\node-token-jwt\app\models\user.js:7
module.export = mongoose.model('User', new Scheme({
^
ReferenceError: Scheme is not defined
at Object.<anonymous> (E:\Eclipse IDE\Enide-Studio-2014.17-luna-SR1-win64-20141011\Enide-Studio-2014.17-luna-SR1-win64\ws\node-token-jwt\app\models\user.js:7:44)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478: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)
at Object.<anonymous> (E:\Eclipse IDE\Enide-Studio-2014.17-luna-SR1-win64-20141011\Enide-Studio-2014.17-luna-SR1-win64\ws\node-token-jwt\server.js:12:14)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
Please help me !
Also see attached of project structure.
server.js
// =======================
// get the packages we need ============
// =======================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('./config'); // get our config file
var User = require('./app/models/user'); // get our mongoose model
// =======================
// configuration =========
// =======================
var port = process.env.PORT || 8080; // used to create, sign, and verify tokens
mongoose.connect(config.database); // connect to database
app.set('superSecret', config.secret); // secret variable
// use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// use morgan to log requests to the console
app.use(morgan('dev'));
// =======================
// routes ================
// =======================
// basic route
app.get('/', function(req, res) {
res.send('Hello! The API is at http://localhost:' + port + '/api');
});
// API ROUTES -------------------
// we'll get to these in a second
// =======================
// start the server ======
// =======================
app.listen(port);
console.log('Magic happens at http://localhost:' + port);
user.js
// get an instance of mongoose and mongoose.Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//set up a mongoose model and pass it using module.exports
module.export = mongoose.model('User', new Scheme({
name : String,
password : String,
admin : Boolean
}));
EDIT-1: I can see the new issue now:
C:\Users\workspace-nod\node-token-jwt\node_modules\mongodb\lib\server.js:242
process.nextTick(function() { throw err; })
^
Error: getaddrinfo ENOTFOUND noder noder:27017
at errnoException (dns.js:27:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:78:26)
Please guide on this.
I am trying to run the serverjs in nodejs by separating the routes and models in different folders, but I am getting the below mentioned error where as i can run the same without moving them to different folders.
Error: Cannot find module '../models/catModel'
at Function.Module._resolveFilename (module.js:339:15)
at Function.Module._load (module.js:290:25)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object.<anonymous> (/home/rajesh/app4/routes/catRoute.js:2:10)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object.<anonymous> (/home/rajesh/app4/cat_server.js:14:12)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
Source Code:
/app4/cat_server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/cats');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var cats = require('../routes/catRoute')(app);
var server = app.listen(3000, function(){ console.log('Sever runnign at localhost:3000'); });
/app4/routes/catRoute.js
var _= require('lodash');
var Cat= require('../models/catModel');
module.exports = function(app) {
/*Create*/
app.post('/cat', function(req, res){
var newCat = new Cat(req.body);
newCat.save(function(err){
if(err){ res.json({info: "error during creating of cat create", error:err}); };
res.json({info: 'Cat created successfully'});
});
});
}
/app4/models/catModel.js
var mongoose = require('mongoose');
var catSchema = mongoose.Schema({ name: String, age: Number, type: String });
module.exports = mongoose.model('Cat', catSchema);
Something doesn't look right with the relative path loading.
Given that /app4/routes/catRoute.js is being loaded correctly with a path of ../routes/catRoute, I suspect that doing the following will help:
var Cat = require('../../models/catModel');
This error comes when path is not right for server
Try this
var Cat = require(process.cwd() + '/models/catModel');
Its resolved, the issue is with my catModel.js file has an additional extension, once I updated its working as expected. Thanks for all your help.