Express renders index.html but no other page - javascript

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

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.

app.get() is not working. related to Difference between app.use and app.get in express.js

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
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);
module.exports = app;
I created express-generator. Then I tried to change app.use('/', indexRouter) → app.get('/', indexRouter) and app.use('/users', usersRouter) → app.get('/users', usersRouter).
Then app.get('/', indexRouter) was working(can hit the URL and get the page information). But app.get('/users', usersRouter) was NOT working. This returned 404 (NotFoundError: Not Found).
I already read this questionDifference between app.use and app.get in express.js
But I couldn't understand
./routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
./routes/users
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
app.use is designed for middlewares and app.get is designed for GET requests. Middlewares are functions that are called before the controller. You may have a middleware to check if the user is authenticate or not, and accept the user's request or deny it.
When you have app.use('/', indexRouter), the indexRouter will be called for all your requests on all your routes. It is like /*.
When you have app.use('/users', usersRouter), the usersRouter will be called for all your requests on all routes that start with /users. It is like /users*.
This is how you can do a GET request:
app.get('/users', (req, res) => res.status(200).send({
message: 'It works.',
}));

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.

app.send is not a function error in WebStorm while writing Node.js code

I am a beginner in Node.js and I am still following tutorials. I did exactly the same thing the tutorial suggested me but I still got this error. This is the error I keep getting every next line and in every next code.
The code written in WebStorm and I just modified two lines in this:
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const 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.get('/', (req, res) => {
app.send('This is a Node Program.');
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
let 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;
The error:
app.send is not a function
TypeError: app.send is not a function
at C:\Users\Tuladhar\WebstormProjects\NodeDemo\app.js:23:8
at Layer.handle [as handle_request] (C:\Users\Tuladhar\WebstormProjects\NodeDemo\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Tuladhar\WebstormProjects\NodeDemo\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\Tuladhar\WebstormProjects\NodeDemo\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Tuladhar\WebstormProjects\NodeDemo\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Tuladhar\WebstormProjects\NodeDemo\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\Tuladhar\WebstormProjects\NodeDemo\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\Tuladhar\WebstormProjects\NodeDemo\node_modules\express\lib\router\index.js:275:10)
at SendStream.error (C:\Users\Tuladhar\WebstormProjects\NodeDemo\node_modules\serve-static\index.js:121:7)
at emitOne (events.js:115:13)
Can someone help me with this error? I might be missing some library files or something. Can some help me to fix this error and suggest me what should be done in order to prevent these errors?
I think you have to send with "res" object like this:
res.send('This is a Node Program.');
Hope it helps.

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

Categories