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.
Related
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');
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'm building my first Node application and having some trouble displaying the page that I want with a GET request. I have installed ejs (opinions welcome on that!) so my understanding is that I do not need to define the 'views' folder. Here is my routes file so far:
const express = require('express');
const router = express.Router();
const Event = require('../models/event')
router.get('/'), function(req, res, next){
/* Event.find({}).then(function(events){
res.send(events);
});
});*/
res.render('../../index');
};
router.post('/events', (req, res) => {
Event.create(req.body);
res.send({type: POST})
});
module.exports = router;
The database is connecting just fine, which I can see with the code that I have commented out in the get request. But for some reason I can't render my index file. My file structure is as follows:
File tree:
So I need to go up two levels, correct? I tried index, index.ejs, ../index, views/index, nothing has worked. What am I doing wrong?
EDIT: this is my server.js:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const routes = require('./routes/index');
var path = require("path");
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(routes);
app.use(bodyParser.urlencoded({extended: true}))
mongoose.connect('mongodb://junk:junk#ds141242.mlab.com:41242/alaska-events');
app.listen(3000, () => {
console.log('listening on 3000')
});
views folder is placed directly in root folder, and using we app.set('views', path.join(__dirname, 'views')); point it to views folder. So in render directly mention the view name.
router.get('/', function(req, res, next){
res.render('index');
});
Thanks for your help everyone, turned out to be just a typo. router.get('/'), function(req, res, next) should have been router.get('/', function(req, res, next).
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
I'm getting started on node JS and facing an issue with io lib, here the error :
ReferenceError: io is not defined
at exports.index (D:\dev\lib\index.js:9:5)
at callbacks (D:\dev\node_modules\express\lib\router\index.js:164:37)
at param (D:\dev\node_modules\express\lib\router\index.js:138:11)
at pass (D:\dev\node_modules\express\lib\router\index.js:145:5)
at Router._dispatch (D:\dev\node_modules\express\lib\router\index.js:1 73:5)
at Object.router (D:\dev\node_modules\express\lib\router\index.js:33:1 0)
at next (D:\dev\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at Object.methodOverride [as handle] (D:\dev\node_modules\express\node_modules\connect\lib\middleware\methodOverride.js:49:5)
at next (D:\dev\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at Object.urlencoded [as handle] (D:\dev\node_modules\express\node_modules\connect\lib\middleware\urlencoded.js:51:37)
Here is the content of my app.js file :
var express = require('express');
var path = require('path');
var app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
fs = require('fs');
app.set('port', process.env.PORT || 8080); app.set('views',
path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon()); app.use(express.logger('dev'));
app.use(express.json()); app.use(express.urlencoded());
app.use(express.methodOverride()); app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', require('./lib').index);
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
my file lib/index.js :
exports.index = function(req, res){
res.render('index');
io.sockets.on('connection', function (socket) {
socket.emit('message', 'welcome');
});
};
Can anyone help me?
You need to pass io to your route:
exports.index = function(io) {
return function(req,res) {
res.render('index');
io.sockets.on('connection', function (socket) {
socket.emit('message', 'welcome');
}
}
}
And then call it as a function in app.get:
app.get('/', require('./lib').index(io));
I'd recommend declaring the require('./lib') part with your other variables. This would allow for code reuse and better readability (which is relative to each person).
var /*other variables*/,
lib = require('./lib');
Then you could just do app.get('/', lib.index(io));
Just a thought.