trying to implement authentication in my web-app using passport, passport-local and pasport-local-mongoose on node.js (using cloud9).
my authentication is successful, but when i'm trying to redirect to other page within my app (redirecting to http://www.google.com works!) i'm getting this stacktrace (need a direction on this):
TypeError: user.get is not a function
at /home/ubuntu/workspace/attendance/v4/node_modules/passport-local-mongoose/index.js:217:21
at pass (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/authenticator.js:347:9)
at Authenticator.deserializeUser (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/authenticator.js:352:5)
at SessionStrategy.authenticate (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/strategies/session.js:53:28)
at attempt (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/middleware/authenticate.js:348:16)
at authenticate (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/middleware/authenticate.js:349:7)
at Layer.handle [as handle_request] (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:312:13)
at /home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:330:12)
at next (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:271:10)
at initialize (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/middleware/initialize.js:53:5)
at Layer.handle [as handle_request] (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:312:13)
at /home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/ubuntu/workspace/attendance/v4/node_modules/express/lib/router/index.js:330:12)
my app.js is the following:
var express = require('express'),
app = express(),
BodyParser = require("body-parser"),
mongoose = require("mongoose"),
students_class = require("./models/class"),
passport= require("passport"),
localstrategy=require ("passport-local"),
// passportlocalmongoose=("passport-local-mongoose"),
student = require ("./models/student");
mongoose.connect("mongodb://localhost/attendance");
app.set("view engine", "ejs");
app.use(express.static ("public"));
app.use(BodyParser.urlencoded({extended: true}));
app.use (require("express-session")( {
secret: "liran",
resave:false,
saveUninitialized:false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new localstrategy(student.authenticate()));
passport.serializeUser(student.serializeUser());
passport.deserializeUser(student.serializeUser());
// ====
// routes
// =====
app.get("/", function(req, res) {
student.find({}, function(err, student) {
if (err) {
console.log(err);
} else {
res.render("home/index.ejs", {
students: student
});
}
});
});
app.post ("/login",passport.authenticate("local"),function (req,res) {
res.redirect("/");
})
and my user model:
var mongoose = require("mongoose"),
passportlocalmongoose=require("passport-local-mongoose")
var studentsSchema = new mongoose.Schema({
username: String,
passport:String
// name: String,
// image: String,
// description:String,
// classes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'class' }]
});
studentsSchema.plugin(passportlocalmongoose);
module.exports= mongoose.model("student", studentsSchema);
Let's check the stack trace to see if we can find a hint:
TypeError: user.get is not a function
at /home/ubuntu/workspace/attendance/v4/node_modules/passport-local-mongoose/index.js:217:21
at pass (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/authenticator.js:347:9)
at Authenticator.deserializeUser (/home/ubuntu/workspace/attendance/v4/node_modules/passport/lib/authenticator.js:352:5)
...
Hmm, deserializeUser might be causing the problem.
Let's look at how it's set up:
passport.serializeUser(student.serializeUser());
passport.deserializeUser(student.serializeUser());
Perhaps you meant to pass student.deserializeUser() to passport.deserializerUser()?
Related
I tried to get the data from a nested array but ended up getting the error type error cannot read property "value" of undefined, I don't know If I calling back in a wrong way but I end up getting the output in console along with the error
const express = require('express');
const app = express();
var bodyParser = require('body-parser');
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
var entries = [{name:"", address:"", month:"", year:""}];
app.get("/", function(req, res){
res.render("homepage");
});
app.get("/addentry", function(req, res){
res.render("add");
});
app.post("/add", function(req, res){
var input = req.body;
var newEntry = {name: input.name, address: input.address, month: input.month, year: input.year};
entries.push(newEntry);
res.redirect("/addentry");
});
app.post("/search", function(req, res){
var search = req.body;
for(var i = 0; i <= entries.length; i++){
console.log(entries[i].name);
}
res.redirect("/addentry");
});
app.listen(3000, function(){
console.log("Server Started Successfully");
});
I end up getting this error always
TypeError: Cannot read property 'name' of undefined
at C:\AllNodeProjects\globalledger\app.js:29:36
at Layer.handle [as handle_request] (C:\AllNodeProjects\globalledger\node_modules\express\lib\router\layer.js:95:5)
at next (C:\AllNodeProjects\globalledger\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\AllNodeProjects\globalledger\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\AllNodeProjects\globalledger\node_modules\express\lib\router\layer.js:95:5)
at C:\AllNodeProjects\globalledger\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\AllNodeProjects\globalledger\node_modules\express\lib\router\index.js:335:12)
at next (C:\AllNodeProjects\globalledger\node_modules\express\lib\router\index.js:275:10)
at C:\AllNodeProjects\globalledger\node_modules\body-parser\lib\read.js:130:5
at invokeCallback (C:\AllNodeProjects\globalledger\node_modules\raw-body\index.js:224:16)
You need to add app.use(bodyParser.json()); after this line => app.use(bodyParser.urlencoded({ extended: true }));
I am trying to set up neo4j databace to use with javescript code.
When I run my code, I keep getting this
PS C:\Users\futur\Documents\Coding\Neo4j> node app.js body-parser
deprecated undefined extended: provide extended option app.js:21:20
Server has started GET / 304 37.114 ms - - { Neo4jError: getaddrinfo
ENOTFOUND locthost locthost:7687
at captureStacktrace (C:\Users\futur\Documents\Coding\Neo4j\node_modules\neo4j-driver\lib\v1\result.js:200:15)
at new Result (C:\Users\futur\Documents\Coding\Neo4j\node_modules\neo4j-driver\lib\v1\result.js:73:19)
at Session._run (C:\Users\futur\Documents\Coding\Neo4j\node_modules\neo4j-driver\lib\v1\session.js:122:14)
at Session.run (C:\Users\futur\Documents\Coding\Neo4j\node_modules\neo4j-driver\lib\v1\session.js:101:19)
at C:\Users\futur\Documents\Coding\Neo4j\app.js:31:4
at Layer.handle [as handle_request] (C:\Users\futur\Documents\Coding\Neo4j\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\futur\Documents\Coding\Neo4j\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\futur\Documents\Coding\Neo4j\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\futur\Documents\Coding\Neo4j\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\futur\Documents\Coding\Neo4j\node_modules\express\lib\router\index.js:281:22
code: 'ServiceUnavailable', name: 'Neo4jError' }
Here is what my code looks like
var express = require("express");
var path = require("path");
var logger = require("morgan");
// var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var neo4j = require("neo4j-driver").v1;
var app = express();
//
// <script src="lib/browser/neo4j-web.min.js"></script>
//view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extened: false}));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
var driver = neo4j.driver("bolt://locthost", neo4j.auth.basic("neo4j", "test"));
var session = driver.session();
//home route
app.get('/', function(req, res){
session
.run("MATCH (n) RETURN n")
.then(function(result){
result.records.forEach(function(records){
console.log(records._fields[0]);
});
})
.catch(function(error){
console.log(error);
});
res.render("index");
});
app.listen(3000);
console.log('Server has started');
module.export = app;
What do I need to do?
You may have a typo in your bolt URI.
If your code is running on the same machine as the neo4j server, try changing locthost to localhost.
I am new to node and need some help in using session. I am using EJS to render my web-pages. Please find my code below.
app.js
var express = require('express');
var registerController = require('./controllers/registerController');
var app =express();
var bodyParser = require('body-parser');
var sessions=require('express-session');
app.set('view engine', 'ejs');
app.use(express.static('./public'));
app.use(sessions({
secret:'asasds*(&^*(',
resave:false,
saveUninitialized:true
}));
app.use(function(req, res, next) {
res.locals.user = req.session.user;
next();
});
//controllers
registerController(app);
app.listen(3000);
console.log( " you are listening to port 3000");
registercontroller.js
var bodyParser = require('body-parser');
var fs = require('fs');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
module.exports=function(app){
app.get('/register',function(req,res){
res.render('register');
});
app.post('/register',urlencodedParser,function(req,res){
console.log(" inside controller :::" );
var userObj = {
"username":req.body.username,
"password":req.body.password,
"email":req.body.email,
"fNmame":req.body.fNmame,
"lNmame":req.body.lNmame
}
console.log(" userObj :::" + JSON.stringify(userObj));
fs.writeFile("/assets/data.txt", JSON.stringify(userObj), function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
var val = req.session.user;
res.render('index2',{session: req.session});
});
};
index2.ejs
<%= JSON.stringify(session) %>
Using all the above I get the below error
<%= JSON.stringify(session) %>
session is not defined
at eval (eval at compile (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:524:12), <anonymous>:24:41)
at returnedFn (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:555:17)
at tryHandleCache (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:203:34)
at View.exports.renderFile [as engine] (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:412:10)
at View.render (c:\learning\socialnetworking\node_modules\express\lib\view.js:128:8)
at tryRender (c:\learning\socialnetworking\node_modules\express\lib\application.js:640:10)
at EventEmitter.render (c:\learning\socialnetworking\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (c:\learning\socialnetworking\node_modules\express\lib\response.js:971:7)
at c:\learning\socialnetworking\controllers\registerController.js:26:13
at Layer.handle [as handle_request] (c:\learning\socialnetworking\node_modules\express\lib\router\layer.js:95:5)
at next (c:\learning\socialnetworking\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (c:\learning\socialnetworking\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (c:\learning\socialnetworking\node_modules\express\lib\router\layer.js:95:5)
at c:\learning\socialnetworking\node_modules\express\lib\router\index.js:281:22
at Function.process_params (c:\learning\socialnetworking\node_modules\express\lib\router\index.js:335:12)
at next (c:\learning\socialnetworking\node_modules\express\lib\router\index.js:275:10)
res.render('register.ejs', {
layout:false,
session: req.session
});
you need to include this basically
I tried connecting it with mlab database but its not working, went through a lot of stackoverflow answers and tried everything but the errors are still there, please help.
var express = require('express');
var mongojs = require('mongojs');
var mongodb = require('mongodb');
// var db = mongojs('contactlist',['contactlist']);
var uri = 'mongodb://user:pass#####.mlab.com:13702/contactlist'
mongodb.MongoClient.connect(uri, { server: { auto_reconnect: true } }, function (err, contactlist) {
});
var db = mongodb.connect(uri);
var app = express();
var bodyParser = require('body-parser');
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.get('/contactlist', function(req, res){
console.log("I received a GET request");
db.contactlist.find(function(err, docs){
console.log(docs);
res.json(docs);
});
});
app.post('/contactlist', function(req, res) {
console.log(req.body);
db.contactlist.insert(req.body,function(err,doc) {
res.json(doc);
});
});
app.listen(process.env.PORT ||3000, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
I am getting these errors after I try inserting data on the browser, its not even displaying the data from the database.
Errors:
TypeError: Cannot read property 'find' of undefined
at D:\contactlistapp\server.js:17:16
at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
at next (D:\contactlistapp\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\contactlistapp\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
at D:\contactlistapp\node_modules\express\lib\router\index.js:281:22
at Function.process_params (D:\contactlistapp\node_modules\express\lib\router\index.js:335:12)
at next (D:\contactlistapp\node_modules\express\lib\router\index.js:275:10)
at jsonParser (D:\contactlistapp\node_modules\body-parser\lib\types\json.js:103:7)
at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
{ name: 'kkm', email: 'kmk' }
TypeError: Cannot read property 'insert' of undefined
at D:\contactlistapp\server.js:27:16
at Layer.handle [as handle_request] (D:\contactlistapp\node_modules\express\lib\router\layer.js:95:5)
at next
db.[collection_name] syntax ( ie. collection name on property ) is supported in MongoShell, but in node environment you must use following syntax:
db.collection("collection_name").find(). The same with insert.
Also note that connect function of MongoClient is async. You must get reference to database from callback that you specified.
mongodb.MongoClient.connect(uri, { server: { auto_reconnect: true } }, function (err, contactlist) {
db = contactlist;
});
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
mongoose.connect("mongodb://localhost/test");
var todoschema = new mongoose.Schema ({
name : {type: String, required: true}
});
var todomodel = mongoose.model('todolist',todoschema);
app.get('/',function(req,res){
res.sendFile('C:/Users/Rohit/Desktop/New folder/public/todo.html');
})
app.get('/todolist', function (req, res){
todomodel.find(function(err,tasks){
res.json(tasks);
});
});
app.post('/todolist', function (req, res) {
todomodel.insert(req.body, function(err, task) {
res.json(task);
});
});
app.delete('/todolist/:id', function (req, res) {
todomodel.remove(req.params.id, function (err, task) {
res.json(task);
});
});
app.get('/todolist/:id', function (req, res) {
todomodel.findById(req.params.id, function (err, task) {
res.json(task);
});
});
app.put('/todolist/:id', function (req, res) {
todomodel.findAndModify({
query: req.params.id,
update: {$set: {name: req.body.name}},
new: true}, function (err, task) {
res.json(task);
}
);
});
app.listen(3000);
console.log("Server running on port 3000");
TypeError: path must be absolute or specify root to res.sendFile
at ServerResponse.sendFile (C:\Users\Rohit\node_modules\express\lib\response.js:403:11)
at C:\Users\Rohit\Desktop\New folder\mong.js:17:9
at Layer.handle [as handle_request] (C:\Users\Rohit\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Rohit\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (C:\Users\Rohit\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Rohit\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Rohit\node_modules\express\lib\router\index.js:277:22
at Function.process_params (C:\Users\Rohit\node_modules\express\lib\router\index.js:330:12)
at next (C:\Users\Rohit\node_modules\express\lib\router\index.js:271:10)
at jsonParser (C:\Users\Rohit\node_modules\body-parser\lib\types\json.js:100:40)
at Layer.handle [as handle_request] (C:\Users\Rohit\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\Rohit\node_modules\express\lib\router\index.js:312:13)
at C:\Users\Rohit\node_modules\express\lib\router\index.js:280:7
at Function.process_params (C:\Users\Rohit\node_modules\express\lib\router\index.js:330:12)
at next (C:\Users\Rohit\node_modules\express\lib\router\index.js:271:10)
at expressInit (C:\Users\Rohit\node_modules\express\lib\middleware\init.js:33:5)
I tried to display a todo.html page by connecting to http://localhost:3000 , but I'm getting an error when i open the http://localhost:3000 page , the error i have uploaded above as a snippet. Can you please guide me on how to display the html file ?
res.sendFile("C:/Users/Rohit/Desktop/New folder/public/todo.html");
UPDATE
try to use
res.sendFile("C:\\Users\\Rohit\\Desktop\\New folder\\public\\todo.html");
#robin
look at the express source code, express/lib/utils.js
exports.isAbsolute = function(path){
if ('/' == path[0]) return true;
if (':' == path[1] && '\\' == path[2]) return true;
if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path
};
It only check the \\, i think it is a bug.