Trying to add a new route to this Express app using the Express app generator. this is the app.js file:
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 routes = require('./routes/index');
var users = require('./routes/users');
var parse = require('./routes/parse');
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('/', routes);
app.use('/users', users);
app.use('/parse', parse);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found - from app.js');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
The lines i added are:
var parse = require('./routes/parse');
app.use('/parse', parse);
Then in the /routes directory i added parse.js that contains:
var express = require('express');
var router = express.Router();
router.get('/parse', function(req, res, next) {
res.send('return from parse.js');
});
module.exports = router;
I can hit the / and the /users resource using a browser and i get the expected result. But when i try to hit /parse i get this 404:
Not Found - from app.js
404
Error: Not Found - from app.js
at /home/bitnami/parsecsvapi/app.js:32:13
at Layer.handle [as handle_request] (/home/bitnami/parsecsvapi/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:312:13)
at /home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:330:12)
at next (/home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:271:10)
at /home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:618:15
at next (/home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:256:14)
at Function.handle (/home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:176:3)
at router (/home/bitnami/parsecsvapi/node_modules/express/lib/router/index.js:46:12)
Try /parse/parse in the URL
If you would like to use /parse, please use / instead of /parse in /routes/parse.js
Please refer /routes/index.js & /routes/users.js.
TL;DR;
app.js
var parse = require('./routes/parse');
app.use('/parse', parse);
routes/parse.js
var express = require('express');
var router = express.Router();
// the URL pattern will be used in conjunction with how its is being used
// in this case it would be '/parse' (from app.js) + '/parse' (as used in the next line)
// resulting in '/parse/parse'
router.get('/parse', function(req, res, next) {
res.send('return from parse.js');
});
module.exports = router;
Related
I used express-generator and the following are app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var app = express();
app.use(cors());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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')));
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// 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;
And when access to http://localhost:5000/api/ got Error:
Not Found
404
NotFoundError: Not Found
at D:\_projects\booking-system\api\app.js:28:8
at Layer.handle [as handle_request] (D:\_projects\booking-system\api\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\_projects\booking-system\api\node_modules\express\lib\router\index.js:317:13)
at D:_projects\booking-system\api\node_modules\express\lib\router\index.js:284:7
at Function.process_params (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:335:12)
at next (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:275:10)
at D:_projects\booking-system\api\node_modules\express\lib\router\index.js:635:15
at next (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:260:14)
at Function.handle (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:174:3)
at router (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:47:12)
Following is routes/index:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'API' });
});
module.exports = router;
Thank you very much for your helps !
The issue is that you define a GET / route in your routes/index.js file and then register it as app.use('/', indexRouter) in your app.js.
So you either change your routes/index.js file to it looks like this:
var express = require('express');
var router = express.Router();
// Note the /api
router.get('/api', function(req, res, next) {
res.render('index', { title: 'API' });
});
module.exports = router;
Or you keep routes/index as it is but your change the way your register it in your main.js to this:
// ...
// Note the /api
app.use('/api', indexRouter);
app.use('/users', usersRouter);
// ...
I have setup new express (nodejs) project and while I tried to run url it shows me an error of 404 not found error. Yet I have not modified any single line of code and directory structure. I have used express-generator command to create express project's structure.
Can anyone provide me suggestions for following issues?
- Why default code does not run?
- How should I setup my project directory to prevent write this long url.
- How could I integrate my chat application with yii1 project.
Following are my code details.
URL : http://localhost:3000/wchat/wnode/users
Directory structure :
wchat/wnode/users
wchat : php project
wnode : node directory to implements instant notification and chat
users : module
Code files :
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 routes = require('./routes/index');
var users = require('./routes/users');
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('/', routes);
app.use('/users', users);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
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;
users.js
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;
Error :
Not Found
404
Error: Not Found
at app.use.res.render.message (/var/www/html/wchat/wnode/app.js:30:13)
at Layer.handle [as handle_request] (/var/www/html/wchat/wnode/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:312:13)
at /var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:330:12)
at next (/var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:271:10)
at /var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:618:15
at next (/var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:256:14)
at Function.handle (/var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:176:3)
at router (/var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:46:12)
Looking at your routes,
app.use('/', routes); -> handlers GET on localhost:3000
app.use('/users', users); -> handles GET on localhost:3000/users
So there is nothing to handle localhost:3000/wchat/wnode/users. Hence the 404.
If you want to handle something like localhost:3000/wchat/wnode/users,
you need to have a route like
router.verb('/wchat/wnode/users', function (req, res, next) {
// handle whatever you want.
});
Looking at your code and what url you are trying to GET, i would really suggest to familiarize yourself with how express handles routing. More info here
I create an express project, but i install the module with command npm install, but when i run node app.js , i cant get foo, can anyone help me ?
the error:
Error: Failed to lookup view "error" in views directory "C:\Users\Jack\Desktop\demo\views"
at EventEmitter.app.render (C:\Users\Jack\Desktop\demo\node_modules\express\lib\application.js:555:17)
at ServerResponse.res.render (C:\Users\Jack\Desktop\demo\node_modules\express\lib\response.js:938:7)
at C:\Users\Jack\Desktop\demo\app.js:55:7
at Layer.handle_error (C:\Users\Jack\Desktop\demo\node_modules\express\lib\router\layer.js:58:5)
at trim_prefix (C:\Users\Jack\Desktop\demo\node_modules\express\lib\router\index.js:300:13)
at C:\Users\Jack\Desktop\demo\node_modules\express\lib\router\index.js:270:7
at Function.proto.process_params (C:\Users\Jack\Desktop\demo\node_modules\express\lib\router\index.js:321:12)
at IncomingMessage.next (C:\Users\Jack\Desktop\demo\node_modules\express\lib\router\index.js:261:10)
at fn (C:\Users\Jack\Desktop\demo\node_modules\express\lib\response.js:933:25)
at EventEmitter.app.render (C:\Users\Jack\Desktop\demo\node_modules\express\lib\application.js:557:14)
and the 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 routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__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('/', routes);
app.use('/users', users);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.get('/foo', function (req, res) {
res.send('Hello World!');
});
module.exports = app;
var port=3000;
var host='localhost';
app.listen(port, host);
console.log('Check url --> ' + host + ':' + port);
whaat's the problem here ? I install all module needed to run app.js but it's not work,plz help me, how can i fix this problem ?
There is a missing error view, the problem is not express, but the example you are running.
Create a file named error.ejs in your folder views.
error.ejs
<h1><%= message %></h1>
<h2><%= error.status %></h2>
<pre><%= error.stack %></pre>
But to get your application running with everything done, every files created and the folder architecture, you should use :
Express generator
MEAN.JS Full-Stack via the MEAN.JS Yo Generator
For the 404 NOT FOUND :
Add thoses files in your views folder. It will allow you to have every errors.
And for your /foo route, I just saw the route is UNDER the 404 not found middleware! Which means it will NEVER go to the route. You should write all your routes in the files of the routes/ folder
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 routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__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('/', routes);
app.use('/users', users);
app.get('/foo', function (req, res) {
res.send('Hello World!');
});
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
var port=3000;
var host='localhost';
app.listen(port, host);
console.log('Check url --> ' + host + ':' + port);
I used the Express generator to generate an express 4 application. Once I did that I replaced the jade templating engine with ejs. I am now trying to add a new route at /players. When I try and navigate to myapp/players I am receiving this error :
Error: Failed to lookup view "error" in views directory "/home/fk/d/e/goose/views"
at EventEmitter.app.render (/home/fk/d/e/goose/node_modules/express/lib/application.js:555:17)
at ServerResponse.res.render (/home/fk/d/e/goose/node_modules/express/lib/response.js:938:7)
at module.exports (/home/fk/d/e/goose/app.js:65:7)
at Layer.handle_error (/home/fk/d/e/goose/node_modules/express/lib/router/layer.js:58:5)
at trim_prefix (/home/fk/d/e/goose/node_modules/express/lib/router/index.js:300:13)
at /home/fk/d/e/goose/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/home/fk/d/e/goose/node_modules/express/lib/router/index.js:321:12)
at IncomingMessage.next (/home/fk/d/e/goose/node_modules/express/lib/router/index.js:261:10)
at fn (/home/fk/d/e/goose/node_modules/express/lib/response.js:933:25)
at EventEmitter.app.render (/home/fk/d/e/goose/node_modules/express/lib/application.js:557:14)
My file structure is
|Myapp"goose"
-bin
-config
-node modules
-public
-routes
--index.js
--users.js
--players.js
-views
--index.ejs
--users.ejs
--players.ejs
--error.ejs
-app.js
-package.json
Here is the code contained in my 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 mongoose = require('mongoose');
var routes = require('./routes/index');
var users = require('./routes/users');
var players = require('./routes/players');
var app = express();
var configDB = require('./config/database.js');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__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('/', routes);
app.use('/users', users);
app.use('/players', players);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Here is the code for my routes/players.js
var express = require('express');
var router = express.Router();
/* GET players page. */
router.get('/players', function(req, res, next) {
res.render('players', { title: 'Players' });
});
module.exports = router;
My index view is currently still working fine. Thank you for your help in advance and please let me know if there is any more information I can provide that would be of assistance.
**EDIT 1: ** I have added an error.ejs file which is reflected above in the file structure. I believe what was causing all the error messages above was my application was trying to render the error.ejs when I was navigating to /players. Now when I am trying to navigate to /players I am being redirected to the new error.ejs view.
Edit 2: This problem has been solved. Please look at user Jonathan Lonowski's answer below for a detailed explanation. Thank you Johnathon.
The initial issue is that requesting GET /players will result in a 404 Not Found.
This is because the route is defined as GET /players/players since Express combines the .use() and router paths:
app.use('/foo', fooRouter);
// GET /foo/bar
fooRouter.get('/bar', ...);
When specifying a "prefix" with .use(), you can define routes for the "root" of that prefix in the router:
// GET /players = /players + /
router.get('/', ...);
I am getting following error when tried to run the node.js application:
Not Found
404
Error: Not Found
at Layer.app.use.res.render.message [as handle] (C:\node\app\app.js:41:15)
at trim_prefix (C:\node\app\node_modules\express\lib\router\index.js:240:15)
at C:\node\app\node_modules\express\lib\router\index.js:208:9
at Function.proto.process_params (C:\node\app\node_modules\express\lib\router\index.js:269:12)
at next (C:\node\app\node_modules\express\lib\router\index.js:199:19)
at next (C:\node\app\node_modules\express\lib\router\index.js:176:38)
at C:\node\app\node_modules\express\lib\router\index.js:137:5
at C:\node\app\node_modules\express\lib\router\index.js:250:10
at next (C:\node\app\node_modules\express\lib\router\index.js:160:14)
at next (C:\node\app\node_modules\express\lib\router\index.js:176:38)
below is my code which i am using in app.js
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/app');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/', routes);
app.use('/users', users);
///var express = require('express');
///var router = express.Router();
/// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
can you please let me what is the root cause of the issue and how this can be resolved.
Below is my router too:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
router.get('/helloworld',function(req,res)
{
res.render('helloworld',{title: 'World of node js' });
});
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
module.exports = router;
If the database processing takes some time, the router will not exist yet to route! So you will need to wait for the database query to process.
I have this in my own app that i'm building in my search router. The queries to fill two drop-downs take about 7-15 seconds, so I'm going to put something like "app initializing" on my index page for 15 seconds...