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);
Related
I am brand new to node and express and I hope that the SO community can help with this very introductory question.
I am simply trying to add an 'about' page with an /about route.
I added app.use('/about', about); in app.js, then created an 'about.js' in the directory 'routes', I added the following to my about.js file (below), and I created an about.jade file.
router.get('/about', function(req, res, next) {
res.render('about');
});
However, when I go to http://localhost:3001/about I get:
Not Found
404
Error: Not Found
my about.jade file is in the views directory along with layout.jade and index.jade.
My files below
/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 about = require('./routes/about');
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.png')));
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('/about', about);
// 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;
routs/about.js:
var express = require('express');
var router = express.Router();
router.get('/about', function(req, res, next) {
res.render('about');
});
module.exports = router;
Any help is appreciated, thanks.
Since you mounted the about router on /about via app.use('/about', about);, you would need to change
router.get('/about', function(req, res, next) {
res.render('about');
});
to something like
router.get('/', function(req, res, next) {
res.render('about');
});
in routes/about.js.
I am using express and I have a catch all route
router.use('*',function(){...});
and a root route
router.use('/', function(){...});
I have this route placed after the
app.use(express.static(path.join(__dirname, 'public')));
this causes my routes to not fire when placed below the previous line. however if I put my routes above it my catch all is also called on static asset requests. is there a way I can catch all requests except for the assets in my public folder including the route '/'? I don't want to resort to using regex and having to update it every time a directory is added to the public directory.
sorry for not being more details here are the relavant 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();
/* This is going to initialize the menubar for nwjs it is currently commented out as this is a non issue at this point
setTimeout(function () {
//initialize passport
var passport = require('./helpers/passport.js');
//setup routes
//setup window menu
console = window.console;
console.log(passport);
passport.init(app);
var gui = window.require('nw.gui');
var win = gui.Window.get();
var menu = new gui.Menu({
type: 'menubar'
});
menu.createMacBuiltin('jist', {
hideEdit: true,
hideWindow: true
});
gui.Window.get().menu = menu;
},1000);*/
// 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;
//window.location.href="http://localhost:3000";
this is my index router
//routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.use('*', function(req, res, nex){
var path = req.originalPath;
if(~['/users/login', '/users/signup'].indexOf(path) || req.user) return next();
if(!req.user) return res.redirect('/users/login');
});
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
My question is less about production code and more of an issue with official documentation for someone who wants to learn a new script or language.
After installing express-generator (0.12.2) and express (4.13.1), I am able to run the following successfully create a new project by running the following command:
npm express example
The example directory is now on my drive and I then change directories and install all default dependencies from the package.JSON file:
cd example && npm install
No problems so far.
I open the app.js file located in the root of my 'example' directory and the Express 4 version of the app.js is as follows:
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: {}
});
});
app.listen(3000)
module.exports = app;
After adding the app.listen(3000); line (second from last line) as learned from a previous thread (Starting Express.js Using app.js or 'npm start'?), running the following command allows me to server the example directory:
node app.js
All is well. However, after visiting the Express documentation, also for version 4 (http://expressjs.com/guide/routing.html), I see the following instructions:
Route paths Route paths, in combination with a request method, define
the endpoints at which requests can be made to. They can be strings,
string patterns, or regular expressions.
Examples of route paths based on strings:
// will match request to the root
app.get('/', function (req, res) {
res.send('root');
});
// will match requests to /about
app.get('/about', function (req, res) {
res.send('about');
});
// will match request to /random.text
app.get('/random.text', function (req, res) {
res.send('random.text');
});
After adding the following line from the Express 4 documentation:
// will match requests to /about
app.get('/about', function (req, res) {
res.send('about');
});
And visiting the following URL:
http://127.0.0.1:3000/about
I receive a 404 not found error, along with an error at line 30, which is:
28 // application routes
29 app.post('/', function(req, res, next) {
30 res.send(req.body);
31 });
Any ideas?
If you added only the code below after app.use like you said, your code should work:
// will match requests to /about
app.get('/about', function (req, res) {
res.send('about');
});
You probably add more code and that could be the problem. Hint: I don't see app.post in your original code.
Here is the code with new app.get for /about route that works:
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);
// will match requests to /about
app.get('/about', function (req, res) {
res.send('about');
});
// 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.listen(3000);
module.exports = app;
i have a 404 problem with EasyRTC on Express.js 4.
The console said : GET /easyrtc/easyrtc.js 404 4.500 ms - 1077
and here's my app.js code :
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 io = require('socket.io');
var easyrtc = require('easyrtc');
var routes = require('./routes/index');
var users = require('./routes/users');
var staticMiddleware = express.static(__dirname + "/public");
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('/easyrtc/*', function (req,res) {
res.sendFile(__dirname + '/static');
})
// 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.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
var webSockets = io.listen(server);
var rtc = easyrtc.listen(app, webSockets);
please help me, i've been searching for the solution all of this time and i couldnt find the solution at all. thanks before
NB : i'm generate express.js project from Terminal in linux , using command : express -e
Well, you may just to remove the code below:
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
I am using angular ui router. The router seems to work perfect on the home page index.html. But any other navigation doesn't work.
Here is my stateprovider angular:
var app = angular.module('myApp', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider
.state("home", {
url: "/",
templateUrl: "../partials/home/index.html"
})
.state("login", {
url:"/login",
templateUrl: "../partials/account/login.html"
})
.state("register", {
url: "/register",
templateUrl: "../partials/account/register.html"
})
.state("values", {
url: "/values",
templateUrl: "../partials/test/values.html"
})
;
});
HTML in my main index.html:
<!--Content -->
<div class="container">
<div ui-view></div>
</div>
<!-- END Content -->
When I navigate the the page localhost:8080/login I get this:
I would think I shouldn't even be seeing this page if it can't find it. Shouldn't it redirect me back to "/" because of $urlRouterProvider.otherwise(). Besides that point though the template url /partials/account/login.html Does Exist.
I am somewhat new to node.js and I am curious if the note file server is trying to route and trumping my angular one? I am using http-server which is probably the most common one.
I am also using Express Node if that helps. And here is the code for app.js where I think the problem may be coming from:
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 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('/', 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;
I figured it out. Doing the below made it work.
app.use(function(req, res) {
// Use res.sendfile, as it streams instead of reading the file into memory.
res.sendfile(__dirname + '/public/index.html');
});
The entire app.js incase anyone is curious where it goes.
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 routes = require('./routes/index');
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) {
// Use res.sendfile, as it streams instead of reading the file into memory.
res.sendfile(__dirname + '/public/index.html');
});
app.use('/', 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);
});
/// 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;
Of course this will need to be in your angular code:
app.config(["$locationProvider", function($locationProvider) {
$locationProvider.html5Mode(true);
}]);
One thing to note that got me. You must restart the server for this to work. ctr+c then paste this code then restart server. Good luck
have you tried using the same directory for your partials :
moving partials/account/login.html" to partials/home/login.html"
Also, are you using your own server.js express configuration, or a yeoman fullstack ?
angular is clearly handling the routing, but it seems that nodejs is not finding the assets...
Be sure to have a specific task for serving partial files in your server.js
function serve_partial(req,res){
var stripped = req.url.split('.')[0];
var requestedView = path.join('./', stripped);
res.render(requestedView, function(err, html) {
if(err) {
res.render('404');
} else {
res.send(html);
}
});
}
function serve_index(req,res){
res.render('index');
}
// Angular Routes
app.get('/partials/*', serve_partial);
app.get('/*', serve_index);
for your case, it might me something as :
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 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')));
function serve_partial(req,res){
var stripped = req.url.split('.')[0];
var requestedView = path.join('./', stripped);
res.render(requestedView, function(err, html) {
if(err) {
res.render('404');
} else {
res.send(html);
}
});
}
app.use('/partials/*', serve_partial);
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;
As i see you request to your node api which there isnt any route like /login and you get 404.
You should try localhost:8080/#/login