node express express.static prevents access from root path '/' - node.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;

Related

Express + node - routing 101

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.

how to serve static files with nodejs in multiple routing

I am trying to make a website of my small bussiness of cables and wires
using nodejs express (ejs)
files are like:
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');
/* routes variables*/
var routes = require('./routes/index');
var cableWires = require('./routes/cableWires');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('public'));
app.use(express.static('public/stylesheets'));
app.use(express.static('public/images'));
app.use(express.static('public/javascripts'));
/* routes */
app.use('/', routes); // index page
app.use('/cableWires', cableWires); //cables and wires
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;
In routes/cablesWires.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('products_cableWires', { title: 'Umesh Electricals' });
});
router.get('/submersible_cables', function(req, res, next) {
res.render('submersible-cables', { title: 'Umesh Electricals' });
});
router.get('/house_wires', function(req, res, next) {
res.render('house-wires', { title: 'Umesh Electricals' });
});
module.exports = router;
When I go to cableWires page, everything is fine,
but when I go to house_wires page or submersible_cables page, it loads the content of ejs file but fails to load static files (css, javascript and images)
What could be the possible mistake am I doing
Its seems that when you make request to any route then it try to fetch that file from that URL path i.e - when you call /route1 then it will call the static file from relative path..so you have to change it to absolute path..
so change the static path and include "/" before static path
app.use(express.static('public')); app.use(express.static('/public/stylesheets')); app.use(express.static('/public/images')); app.use(express.static('/public/javascript
Let us know if its help

Browser doesn't show index page made by index.js and index.jade on Node.js

I'd like to show index page by index.js and index.jade on Node.js, however browser returns the page only show index.html as attached picture.
I set the index.js as routes as following, thus I think the root path should return index page.
var routes = require('./routes/index');
app.use('/', sessionCheck, routes);
The following is my present code. Could you tell me what is the problem?
###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 session = require('express-session');
var routes = require('./routes/index');
var users = require('./routes/users');
var login = require('./routes/login');
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(__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({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 30 * 60 * 1000 // 30min.
}
}));
var sessionCheck = function(req, res, next) {
if (req.session.user) {
next();
} else {
res.redirect('/login');
}
};
app.use('/login', login);
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;
###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;
###views/index.jade
extends layout
block content
h1= title
p Welcome to #{title}
I've found the problem.
Becuase I set the root directory '/public', I could not access index.js.Thank you for you kindeness.
app.use(express.static(path.join(__dirname, 'public')));

Express Routing with Standard Express.js 4 (generator) Installation Not Working

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;

http://localhost:3000/api/posts i am getting COULD NOT GET ANY RESPONSE. using POSTMAN

// this is app.js which is the main application 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 api = require('./routes/api');``
//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('/api', api);
// 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;
and this is api.js which implements the RESTful API.Post is a resource and because of this we will implement a /posts API which will First we'll implement placeholder route handlers for the /posts api within api.js.
var express = require('express');
var router = express.Router();
//api for all posts
router.route('/posts')
//create a new post
.post(function(req, res){
//TODO create a new post in the database
res.json({message:"TODO create a new post in the database"});
})
.get(function(req, res){
//TODO get all the posts in the database
res.json({message:"TODO get all the posts in the database"});
})
module.exports = router;
i am getting this on postman
You should be going to
http://localhost:3000/api/posts
Not
http://localhost:3000/routes/api/posts
..
Edit:
I didn't realize you're trying to call
req.send
Well that is not a method of
req (request)
You're looking for
res (response)
And on top of that you're trying to send a json result, not plain text so use
res.json
Instead of
res.send
I don't see you starting the server with app.listen(3000). You merely export the express app.
Or is there a different module that spins up the server?

Resources