connecting Neo4j to nodejs error - javascript

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.

Related

JS, Express: Failed to lookup view in directory regardless following guide

Im following this guide:
https://appdividend.com/2017/06/18/node-js-express-tutorial/
And did a lot of research but somehow can't get it working.
My folder structure:
My code:
// app.js
var express = require('express');
var app = express();
var port = 3000;
app.use(express.static('public'));
app.listen(port, function(){
console.log('Server is running on port:', port);
})
app.get('/', function(req, res){
res.send('Hello Express');
});
app.set('view engine', 'ejs');
var itemRouter = express.Router();
app.use('/items', itemRouter);
itemRouter.route('/').get(function (req, res) {
res.render('items');
});
itemRouter.route('/single').get(function (req, res) {
res.render('singleItem');
});
My output:
Error: Failed to lookup view "items" in views directory "C:\Users\Karol\views"
at Function.render (C:\Users\Karol\node_modules\express\lib\application.js:580:17)
at ServerResponse.render (C:\Users\Karol\node_modules\express\lib\response.js:1008:7)
at C:\Users\Karol\Desktop\CB\app.js:27:7
at Layer.handle [as handle_request] (C:\Users\Karol\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Karol\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\Karol\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Karol\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Karol\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\Karol\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\Karol\node_modules\express\lib\router\index.js:275:10)
This is what I get when I visit localhost:port/items (replace port with actual port number).
There is a problem about resolving views path. Try to require path module after express
var express = require('express');
var path = require('path');
var app = express();
var port = 3000;
and after setting ejs template add this:
app.set('view engine', 'ejs');
app.set('views', path.resolve(__dirname, 'views'));
Replace :
app.use('/items', itemRouter);
itemRouter.route('/').get(function (req, res) {
res.render('items');
});
itemRouter.route('/single').get(function (req, res) {
res.render('singleItem');
});
by :
itemRouter.route('/items/').get(function (req, res) {
res.render('items');
});
itemRouter.route('/items/single').get(function (req, res) {
res.render('singleItem');
});
var path = require('path');
Try this to set the directory for the public like this.
app.set('view_engine', 'ejs');
app.set('views', path.join(__dirname,'/views'))
It will get the project directory and set the views path.

Express renders index.html but no other page

I have an express app to just serve static html files.
let express = require('express');
let path = require('path');
let cookieParser = require('cookie-parser');
let logger = require('morgan');
let indexRouter = require('./routes/index');
let usersRouter = require('./routes/users');
let appRouter = require('./routes/app');
let app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/app', appRouter);
module.exports = app;
In /public I have index.html and app.html
In /routes/ I have index.js and app.js
Both of them are basically identical
index.js
let express = require('express');
let router = express.Router();
router.get('/', function (req, res, next) {
res.render('index');
});
module.exports = router;
app.js
let express = require('express');
let router = express.Router();
router.get('/', function (req, res, next) {
res.render('app');
});
module.exports = router;
When I access localhost:3000 the index.html file is displayed perfectly.
When I access localhost:3000/app I get the error
Error: No default engine was specified and no extension was provided.
at new View (C:\a\Web\todo\node_modules\express\lib\view.js:61:11)
at Function.render (C:\a\Web\todo\node_modules\express\lib\application.js:570:12)
at ServerResponse.render (C:\a\Web\todo\node_modules\express\lib\response.js:1008:7)
at C:\Voliware\Web\todo\routes\app.js:5:9
at Layer.handle [as handle_request] (C:\a\Web\todo\node_modules\express\lib\router\layer.js:95:5)
at next (C:\a\Web\todo\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\a\Web\todo\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\a\Web\todo\node_modules\express\lib\router\layer.js:95:5)
at C:\a\Web\todo\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\a\Web\todo\node_modules\express\lib\router\index.js:335:12)
You said 'just serve static html files.'. then mark the following 3 lines.
// app.use('/', indexRouter);
// app.use('/users', usersRouter);
// app.use('/app', appRouter);
and access access localhost:3000/app.html not access localhost:3000/app. because you don't have a static file named 'app'.
Try adding this to your middle ware stack
app.set('view engine', 'html');

Using session in EJS with node

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

Unable to set separate route files in Express JS

I want to separate my login route from default app.js and route/index.js files but I'm not getting error 404 Not Found while executing localhost:3000/login
I know this questions has been asked already before and I've followed other answers on StackOverflow but not getting why I'm getting error.
Stack overflow question I followed:
How to separate routes on Node.js and Express 4?
I'm not getting why I'm getting this error.
app.js
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 expressValidator = require('express-validator');
var session = require('express-session');
var mongodb = require('./mongoDB');
var index = require('./routes/index');
var users = require('./routes/users');
var login = require('./routes/login'); //including login.js
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/public')));
app.use(session({
name: 'mysession',
secret: 'some_secret',
saveUninitialized: false,
resave: true, cookie: {
secure: true
}}));
app.use('/', index);
app.use('/users', users);
app.use('/login', login);
mongodb.connectDatabase;
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
route/login.js
var express = require('express');
var router = express.Router();
router.get('/login', function (req, res) {
res.send('exec');
});
module.exports = router;
localhost:3000/login
Not Found
404
Error: Not Found
at /home/jatin/Drive/OpenSource/sessionManager/app.js:44:13
at Layer.handle [as handle_request] (/home/jatin/Drive/OpenSource/sessionManager/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/jatin/Drive/OpenSource/sessionManager/node_modules/express/lib/router/index.js:312:13)
at /home/jatin/Drive/OpenSource/sessionManager/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/jatin/Drive/OpenSource/sessionManager/node_modules/express/lib/router/index.js:330:12)
at next (/home/jatin/Drive/OpenSource/sessionManager/node_modules/express/lib/router/index.js:271:10)
at /home/jatin/Drive/OpenSource/sessionManager/node_modules/express/lib/router/index.js:618:15
at next (/home/jatin/Drive/OpenSource/sessionManager/node_modules/express/lib/router/index.js:256:14)
at Function.handle (/home/jatin/Drive/OpenSource/sessionManager/node_modules/express/lib/router/index.js:176:3)
at router (/home/jatin/Drive/OpenSource/sessionManager/node_modules/express/lib/router/index.js:46:12)
at Layer.handle [as handle_request] (/home/jatin/Drive/OpenSource/sessionManager/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/jatin/Drive/OpenSource/sessionManager/node_modules/express/lib/router/index.js:312:13)
at /home/jatin/Drive/OpenSource/sessionManager/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/jatin/Drive/OpenSource/sessionManager/node_modules/express/lib/router/index.js:330:12)
at next (/home/jatin/Drive/OpenSource/sessionManager/node_modules/express/lib/router/index.js:271:10)
at /home/jatin/Drive/OpenSource/sessionManager/node_modules/express/lib/router/index.js:618:15
It's a little confusing, but when you use:
app.use('/login', login);
You are nesting all routes defined in login under the /login namespace. You can probably currently access the route at /login/login
Change your login.js to:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.send('exec');
});
module.exports = router;
Then /login/ will correctly be routed to the / route of the login namespace

Nodejs / Express - Launching my app: express.createServer() is deprecated

I downloaded a node app to test and play around with. I have googled around and found that Express is found to be a little outdated. Can someone help me to fix the implemented code?
Here is the code
/**
* Module dependencies.
*/
// base dependencies for app
var express = require('express')
, routes = require('./routes')
, DB = require('./accessDB').AccessDB
, passport = require('passport')
, mongoose = require('mongoose')
, mongoStore = require('connect-mongodb');
var app = module.exports = express.createServer();
global.app = app;
var DB = require('./accessDB');
var conn = 'mongodb://localhost/CrowdNotes';
var db;
// SocketIO Configuration
//var io = require('socket.io').listen(app);
//
//io.sockets.on('connection', function(socket) {
// socket.on('user note', function (note) {
// console.log(note);
// });
//});
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(require('stylus').middleware({ src: __dirname + '/public' }));
app.use(express.session({
store: mongoStore(conn)
, secret: 'applecake'
}, function() {
app.use(app.router);
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/public'));
});
db = new DB.startup(conn);
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
require('./routes')(app);
app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
And here is the error I receive once running the app via node app
C:\CrowdNotes>node app
Warning: express.createServer() is deprecated, express
applications no longer inherit from http.Server,
please use:
var express = require("express");
var app = express();
C:\CrowdNotes\app.js:63
console.log("Express server listening on port %d in %s mode", app.address().po
^
TypeError: Object function app(req, res){ app.handle(req, res); } has no method
'address'
at Object.<anonymous> (C:\CrowdNotes\app.js:63:67)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
C:\CrowdNotes>
FIXED.
I am now at the point where I register, and go to login using my new 'User' data and receive this error:
ReferenceError: C:\CrowdNotes\views\account.jade:6
4| div#header
5| h2 CrowdNotes
> 6| p Hi, #{currentUser.name.first}!
7|
8| - if (myEvent)
9| p.center My Event: #{myEvent.name}
currentUser is not defined
at eval (eval at <anonymous> (C:\CrowdNotes\node_modules\jade\lib\jade.js:176:8))
at exports.compile (C:\CrowdNotes\node_modules\jade\lib\jade.js:181:12)
at Object.exports.render (C:\CrowdNotes\node_modules\jade\lib\jade.js:216:14)
at View.exports.renderFile [as engine] (C:\CrowdNotes\node_modules\jade\lib\jade.js:243:13)
at View.render (C:\CrowdNotes\node_modules\express\lib\view.js:75:8)
at Function.app.render (C:\CrowdNotes\node_modules\express\lib\application.js:500:10)
at ServerResponse.res.render (C:\CrowdNotes\node_modules\express\lib\response.js:716:7)
at module.exports.getAccount (C:\CrowdNotes\routes\index.js:47:11)
at Promise.module.exports.getMyEvent (C:\CrowdNotes\accessDB.js:54:7)
at Promise.addBack (C:\CrowdNotes\node_modules\mongoose\lib\promise.js:128:8)
I'm wondering if this is some form of syntax error too? Not sure what's gone wrong here as I thought the code all lined up tbh.
I am using the code from here: https://github.com/rockbot/crowdnotes
The solution is given in the error.
Warning: express.createServer() is deprecated, express
applications no longer inherit from http.Server
please use:
var express = require("express");
var app = express();
So you will have to just do this.
var express = require('express')
, http = require('http');
var app = express();
var server = http.createServer(app);
Its can done with this simple program:
var express = require('express');
var app = express();
app.get('/',
function(req,res)
{
res.send("express");
}
);
app.listen(3333);
it works fine.
Another potential solution to this is to install express 2.5.8 as a dependency.
Add to package.json:
{
"name": "authentication"
, "version": "0.0.1"
, "private": true
, "dependencies": {
"express": "2.5.8"
, "jade": ">= 0.26.1"
}
}
and then run
npm install
var express = require('express');
var app = express();
app.listen(your_port_number);
With the newer release of express (express 4.x), you do not need to create server. app.listen internally does that. Refer https://expressjs.com/en/4x/api.html#app.listen
I am already using the following snippet and it is working fine:
var express =require("express");
var http = require("http");
var app = express();
//app routers here
...
var httpServer = http.Server(app);
httpServer.listen({PORT}, function(err){
});

Categories