Using session in EJS with node - javascript

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

Related

getting a type error when calling back data from an array

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 }));

connecting Neo4j to nodejs error

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.

Getting error while creating node in neo4j using node js

My Code!!
var neo4j = require('neo4j-driver').v1;
var express = require('express');
var logger = require('morgan');
var path = require('path');
var bodyParser =require('body-parser');
var app=express();
app.set('views',path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname,'public')));
var driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("Novasys", "123456"));
var session = driver.session();
app.get('/', function(req,res){
session
.run('MATCH (n:Movie) RETURN n LIMIT 30')
.then(function(result){
var moviearr = [];
result.records.forEach(function(record){
moviearr.push({enter code here
id: record._fields[0].identity.low,
title: record._fields[0].properties.title,
released: record._fields[0].properties.released
});
});
session
.run('MATCH (n:Person) RETURN n LIMIT 25')
.then(function(result2){
var personArr = [];
result2.records.forEach(function(record){
personArr.push({
id: record._fields[0].identity.low,
name: record._fields[0].properties.name
});
});
res.render('index', {
movies: moviearr,
persons: personArr
});
})
.catch(function(err){
console.log(err);
});
})
.catch(function(err){
console.log(err);
});
});
app.post('/movie/add',function(req,res,next){
var title = req.body.title;
var released = req.body.released;
session
.run('CREATE(n:Movie {title:{titleParam}, released:{releasedParam}}) RETURN n.title',{titleParam:title, releasedParam:released})
.then(function(result){
res.redirect();
session.close();
})
.catch(function(err){
console.log(err);
});
res.redirect('/');
});
app.listen(4000);
console.log('Server started on port 4000');
module.exports=app; **strong text**
getting error!!
TypeError: Cannot read property 'name' of undefined
at B:\nodejs\newp\app.js:75:30
at Layer.handle [as handle_request] (B:\nodejs\newp\node_modules\express\lib\router\layer.js:95:5)
at next (B:\nodejs\newp\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (B:\nodejs\newp\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (B:\nodejs\newp\node_modules\express\lib\router\layer.js:95:5)
at B:\nodejs\newp\node_modules\express\lib\router\index.js:277:22
at Function.process_params (B:\nodejs\newp\node_modules\express\lib\router\index.js:330:12)
at next (B:\nodejs\newp\node_modules\express\lib\router\index.js:271:10)
at serveStatic (B:\nodejs\newp\node_modules\serve-static\index.js:75:16)
at Layer.handle [as handle_request] (B:\nodejs\newp\node_modules\express\lib\router\layer.js:95:5)
Can anyone help me in solving this. I am new to node js as well as neo4j.
Thanks in Advance
☼ Hello,
Do you have a label "Person" in your Neo4j database ?
session
.run('MATCH (n:Person) RETURN n LIMIT 25')
Have you tried with :
session
.run('MATCH (n:Actor) RETURN n LIMIT 25')
I think you took this exemple here, but they use the labels "Movies" and "Actors"

TypeError: path must be absolute or specify root to res.sendFile

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.

BodyParser urlencode in express 4 and encoding windows-1251

External service makes a request to my application , and the POST request body encoding winows- 1251 , but as I understand it , body-parser does not work with windows-1251, and i get a error
POST /api/v1/payment/result 415 76.170 ms - 3073
UnsupportedMediaTypeError: unsupported charset "WINDOWS-1251"
at urlencodedParser (/home/keler/ask-landing/node_modules/body-parser/lib/types/urlencoded.js:102:12)
at Layer.handle [as handle_request] (/home/keler/ask-landing/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/keler/ask-landing/node_modules/express/lib/router/index.js:312:13)
at /home/keler/ask-landing/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/keler/ask-landing/node_modules/express/lib/router/index.js:330:12)
at next (/home/keler/ask-landing/node_modules/express/lib/router/index.js:271:10)
at jsonParser (/home/keler/ask-landing/node_modules/body-parser/lib/types/json.js:107:37)
at Layer.handle [as handle_request] (/home/keler/ask-landing/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/keler/ask-landing/node_modules/express/lib/router/index.js:312:13)
at /home/keler/ask-landing/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/keler/ask-landing/node_modules/express/lib/router/index.js:330:12)
at next (/home/keler/ask-landing/node_modules/express/lib/router/index.js:271:10)
at logger (/home/keler/ask-landing/node_modules/morgan/index.js:144:5)
at Layer.handle [as handle_request] (/home/keler/ask-landing/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/keler/ask-landing/node_modules/express/lib/router/index.js:312:13)
at /home/keler/ask-landing/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/keler/ask-landing/node_modules/express/lib/router/index.js:330:12)
at next (/home/keler/ask-landing/node_modules/express/lib/router/index.js:271:10)
at expressInit (/home/keler/ask-landing/node_modules/express/lib/middleware/init.js:33:5)
at Layer.handle [as handle_request] (/home/keler/ask-landing/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/keler/ask-landing/node_modules/express/lib/router/index.js:312:13)
at /home/keler/ask-landing/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/keler/ask-landing/node_modules/express/lib/router/index.js:330:12)
at next (/home/keler/ask-landing/node_modules/express/lib/router/index.js:271:10)
at query (/home/keler/ask-landing/node_modules/express/lib/middleware/query.js:49:5)
at Layer.handle [as handle_request] (/home/keler/ask-landing/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/keler/ask-landing/node_modules/express/lib/router/index.js:312:13)
at /home/keler/ask-landing/node_modules/express/lib/router/index.js:280:7
Prompt decision
I bring your own code .
in App
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var bb = require('express-busboy');
var routes = require('./routes/index');
var app = express();
// view engine setup
var engines = require('consolidate');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../client')));
bb.extend(app);
require("./config/db.js")();
app.use('/', require('./routes'));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
var server = app.listen(3000, function() {
console.log('Express server listening on port ' + server.address().port);
});
module.exports = app;
in Route
var payment = {
result : function(req, res, next) {
console.log(req.body);
res.send("ok");
}
}
module.exports = payment;

Categories