In my application, when i try to call the service I am getting the error as like this:
module.js:327
throw err;
^
Error: Cannot find module '/api/sessions'
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (C:\Tutorials\try\ModernWebApp\server.js:13:9)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
[14:38:53] [nodemon] app crashed - waiting for file changes before starting...
here is my server.js file:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(express.static( __dirname + '/assets'))
app.use(express.static( __dirname + '/templates'))
app.use(bodyParser.json());
//if i remove both this 2 lines, no issues come.
app.use(require('/api/sessions', require( __dirname + '/controllers/api/sessions')));
app.use(require('/api/users', require('./controllers/api/users')));
app.get('/', function( req, res ){
res.sendFile( __dirname + '/layouts/app.html');
})
app.listen( 8888, function(){
console.log('app listening!' + 8888 );
})
what is wrong here, how to solve this. the 2 files are nothing but to handling the query from front end.
session.js for sample:
var router = require('express').Router();
var bcrypt = require('bcryptjs');
var jwt = require('jwt-simple');
var User = require('../../models/user');
var config = require('../../config');
router.post('/sessions', function( req, res, next ) {
User.findOne({
username: req.body.username,
}).select('password').select('username')
.exec(function( err, user ) {
if( err ) { return next( err )}
if(!user) { return res.send(401)}
bcrypt.compare(req.body.password, user.password, function( err, valid ) {
if( err ) { return next( err )}
if(!valid) { return res.send(401)}
var token = jwt.encode({username:user.username}, config.secret);
res.send( token );
})
})
});
module.exports = router;
try using just.
app.use(require('/api/sessions'));
app.use(require('/api/users'));
If that doesn't work give the proper path of the module you want to require.Because require function only take one parameter that is a module ID in string.
https://nodejs.org/api/modules.html#modules_module_require_id
you just use require('/api/sessions'), so node will look for sessions.js file in your root dir(/) not your work directory.
maybe you should try require('./api/sessions')
Related
Hello I'm having a silly problem but I can't find the solution. When I try start my localhost I get an error saying this :
Error: Cannot find module 'passport'
Require stack:
- D:\Other\Projects\Code\Powershell\shopping-cart\config\passport.js
- D:\Other\Projects\Code\Powershell\shopping-cart\routes\index.js
- D:\Other\Projects\Code\Powershell\shopping-cart\app.js
- D:\Other\Projects\Code\Powershell\shopping-cart\bin\www
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:982:15)
at Function.Module._load (internal/modules/cjs/loader.js:864:27)
at Module.require (internal/modules/cjs/loader.js:1044:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\config\passport.js:1:16)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Module.require (internal/modules/cjs/loader.js:1044:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\routes\index.js:5:16)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'D:\\Other\\Projects\\Code\\Powershell\\shopping-cart\\config\\passport.js',
'D:\\Other\\Projects\\Code\\Powershell\\shopping-cart\\routes\\index.js',
'D:\\Other\\Projects\\Code\\Powershell\\shopping-cart\\app.js',
'D:\\Other\\Projects\\Code\\Powershell\\shopping-cart\\bin\\www'
}
I understand that it is not finding the passport.js file, I have checked the path name more than 10 times and I saw another problem where the guy had not installed the passport module, so I did that as well but it is still throwing the same error. This is what my index.js looks like :
var express = require('express');
var router = express.Router();
var Product = require('D:/Other/Projects/Code/Powershell/shopping-cart/models/product');
var csrf = require('csurf');
var passport = require('D:/Other/Projects/Code/Powershell/shopping-cart/config/passport.js');
var csrfProtection = csrf();
router.use(csrfProtection);
/* GET home page. */
router.get('/', function(req, res, next) {
Product.find(function(err, docs) {
var productChunks = [];
var chunkSize = 3;
for (var i = 0; i < docs.length; i += chunkSize) {
productChunks.push(docs.slice(i, i + chunkSize));
}
res.render('shop/index', { title: 'Shopping Cart', products: productChunks });
});
});
router.get('/user/signup', function (req, res, next) {
res.render('user/signup', {csrfToken: req.csrfToken()});
});
router.post('/user/signup', passport.authenticate('local.signup', {
successRedirect: '/user/profile',
failureRedirect: '/user/signup',
failureFlash: true
}));
router.get('/user/profile', function(req, res, next) {
res.render('user/profile');
});
module.exports = router;
Any help would be appreciated, thanks! Also , I have another problem , can I post another question in like one hour? (is it allowed to have more than 1 questions posted?)
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();
});
};
I keep getting the above error when trying to run my app, can't figure out what package I haven't added..
The server was working perfectly fine before adding this document, so im hoping its an issue with this document and not something else.
Its a npm called node-scheduler
var express = require('express');
var router = express.Router()
var path = require('path');
var bodyParser = require('body-parser');
var db = require('mongoskin').db("localhost/awl-loan-system", { w: 0});
db.bind('event');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.get('/init', function(req, res){
db.event.insert({
text:"My test event A",
start_date: new Date(2013,8,1),
end_date: new Date(2013,8,5)
});
db.event.insert({
text:"My test event B",
start_date: new Date(2013,8,19),
end_date: new Date(2013,8,24)
});
db.event.insert({
text:"Morning event",
start_date: new Date(2013,8,4,4,0),
end_date: new Date(2013,8,4,14,0)
});
db.event.insert({
text:"One more test event",
start_date: new Date(2013,8,3),
end_date: new Date(2013,8,8),
color: "#DD8616"
});
res.send("Test events were added to the database")
});
app.get('/data', function(req, res){
db.event.find().toArray(function(err, data){
//set id property for all records
for (var i = 0; i < data.length; i++)
data[i].id = data[i]._id;
//output response
res.send(data);
});
});
app.post('/data', function(req, res){
var data = req.body;
var mode = data["!nativeeditor_status"];
var sid = data.id;
var tid = sid;
delete data.id;
delete data.gr_id;
delete data["!nativeeditor_status"];
function update_response(err, result){
if (err)
mode = "error";
else if (mode == "inserted")
tid = data._id;
res.setHeader("Content-Type","text/xml");
res.send("<data><action type='"+mode+"' sid='"+sid+"' tid='"+tid+"'/>
</data>");
}
if (mode == "updated")
db.event.updateById( sid, data, update_response);
else if (mode == "inserted")
db.event.insert(data, update_response);
else if (mode == `enter code here`"deleted")
db.event.removeById( sid, update_response);
else
res.send("Not supported operation");
});
returning this error
D:\One31\Clients\A W Lymn\node_modules\express\lib\express.js:107
throw new Error('Most middleware (like ' + name + ') is no longer bundled
with Express and must be installed separately. Please see
https://github.com/senchalabs/connect#middleware.');
^
Error: Most middleware (like bodyParser) is no longer bundled with Express
and must be installed separately. Please see
https://github.com/senchalabs/connect#middleware.
at Function.get (D:\One31\Clients\A W
Lymn\node_modules\express\lib\express.js:107:13)
at Object.<anonymous> (D:\One31\Clients\A W Lymn\routes\calendar.js:12:16)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\One31\Clients\A W Lymn\routes\index.js:6:16)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
Any help?
You're already including the separate body-parser module, so use bodyParser.urlencoded({ extended: false })/bodyParser.json() instead of express.bodyParser().
You need to install body-parser separately by running
npm i body-parser -S
The -S flag adds the package to your package.json file
i am learning node and i have two get request in my index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.status(200)
.json({
status: 'success',
message: 'Welcome to EverestApi!'
});
});
var db = require('./queries');
router.get('/api/users', db.getAllUsers);
router.get('/api/pref', db.getAllPref);
module.exports = router;
and my query.js
var promise = require('bluebird');
var options ={
promiseLib : promise
};
var pgp = require('pg-promise')(options);
var db = pgp({
host: 'localhost',
port: 5432,
database: 'nari',
user: 'postgres',
password: 'pes'
});
function getAllUsers(req, res, next) {
db.any('SELECT * FROM office.users')
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved all users'
});
})
.catch(function (err) {
return next(err);
});
}
function getAllPref(req, res, next){
db.any('SELECT * FROM core.preferences')
.then(function(data){
res.status(200)
.json({
status: 'success',
data : data,
message : 'Retrieved all preferences'
});
})
.catch(function(err){
return next(err);
});
}
module.exports ={getAllUsers: getAllUsers};
module.exports={getAllPref : getAllPref};
I have two GET Action in here.One getAllUsers() and another getAllPref().Starting the server gives error .
D:\node-postgress-promises\node_modules\express\lib\router\route.js:202
throw new Error(msg);
^
Error: Route.get() requires callback functions but got a [object Undefined]
at Route.(anonymous function) [as get] (D:\node-postgress-promises\node_modules\express\lib\router\route.js:202:15)
at Function.proto.(anonymous function) [as get] (D:\node-postgress-promises\node_modules\express\lib\router\index.js:510:19)
at Object. (D:\node-postgress-promises\api\index.js:17:8)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object. (D:\node-postgress-promises\server.js:6:11)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
If i comment one of the above routes for eg . router.get('/api/users', db.getAllUsers);
I get the response..Any Help please..I know this is naive but i am still learning and very new to this.Pardon if too naive.Thank you
in your query.js
export the functions in a object
module.exports = {
getAllUsers: getAllUsers,
getAllPref: getAllPref,
}
Im trying to create auto increment field in mongoose but i cant create for some reason
This is my app.js
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Artist = require('./models/artist');
mongoose.connect('mongodb://localhost/auto-increment');
app.get('/', function(req, res){
Artist.create({
name: "artistName",
fpimage: "Cover"
}, function(err, artist){
if(err) {
console.log(err);
} else {
artist.save();
console.log(artist);
res.send('Hi ')
}
});
});
// Set Port
app.set('port', (process.env.PORT || 3000));
// Run Server
app.listen(app.get('port'), function(){
console.log('Server has started on Port: '+app.get('port'));
});
and this is my artist model
var mongoose = require("mongoose");
var autoIncrement = require('mongoose-auto-increment');
var artistSchema = new mongoose.Schema({
name: String,
fpimage: String
});
artistSchema.plugin(autoIncrement, 'Artist');
module.exports = mongoose.model('Artist', artistSchema);
When i run the app, i get following the error message
fn(this, opts);
^
TypeError: fn is not a function
at Schema.plugin (C:\Users\tjesu\Desktop\pidal\auto-increment\node_modules\mongoose\lib\schema.js:1060:3)
at Object.<anonymous> (C:\Users\tjesu\Desktop\pidal\auto-increment\models\artist.js:10:14)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:\Users\tjesu\Desktop\pidal\auto-increment\app.js:4:14)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.runMain (module.js:575:10)
How can i fix this error? What should i do?
From the docs, it looks like you're missing two things:
You need to initialize autoIncrement:
autoIncrement.initialize(mongoose.connection);
You need to change your call to:
artistSchema.plugin(autoIncrement.plugin, 'Artist');
use autoIncrement.plugin instead of autoIncrement in your model
like:
artistSchema.plugin(autoIncrement.plugin, 'Artist');
and need initialize autoIncrement once
var connection = mongoose.createConnection("mongodb://localhost/auto-increment");
autoIncrement.initialize(connection);
and can use get like
app.get('/', function(req, res){
var artist = new Artist({name: "Telmuun",fpimage: "Cover"});
artist.save(function(err, saved) {
if(err) {
console.log(err);
}
else {
res.send('saved');
}
});
});