is is possible to extract express use into another file? - node.js

I'm having a simple express app but I think the file is so messy and I'm trying to organize it
so for example this piece of code
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(errorHandler());
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
is it possible to separate it into another file and require it on the main file?

Yes, you can try specifying the directory name, I mean something like:
http://localhost:3001/styles.css
To have /styles in your request URL, you can use:
app.use("/styles", express.static(__dirname + '/styles'));
Other method could be:
//Serve static content for the app from the "public" directory in the application directory.
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
// Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static".
// GET /static/style.css etc.
app.use('/static', express.static(__dirname + '/public'));
app.use('/img',express.static(path.join(__dirname, 'public/images')));
app.use('/js',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/css',express.static(path.join(__dirname, 'public/stylesheets')));
Then just test the Static request example in socket.io or other of your preference:
http://testexpress.lite.c9.io/js/socket.io.js

Related

NodeJS and Express: Add auth middleware to static path

I have a node app running express as the web app framework and I use Stormpath for authentication.
Storm path gives the ability to protect a route with several middlewares,
for example:
router.get('/user_data_api', stormpath.apiAuthenticationRequired, function(req, res) {
res.send('hello you are authenticated!");
});
});
What I want to do is to add authenticationRequired as a middleware to the static definition of express:
app.use(express.static(__dirname + '/public'));
This could be achieved by adding a route to the static assets, so if I have a file ./public/index.html I can set the route like this:
app.use('/secured-assets',
stormpath.auth_fn, express.static(__dirname + '/public'));
But then the file will be in
www.mydomain.com/secured-assets/index.html
And I want it in
www.mydomain.com/index.html
Help?
Do just:
app.use(stormpath.auth_fn, express.static(__dirname + '/public'));
It'll add stormpath.auth_fn and express.static(__dirname + '/public') middlewares to the / path and, hence, will protect every route.
This worked for me with Express ^4.13.4 and Stormpath ^3.1.2
app.use(stormpath.loginRequired, express.static(__dirname + '/public'));

Serve static content and views from same directory?

Is it possible to serve static content and views from the same directory?
I found a partial solution below:
//Enable Express static content serving:
app.use(express.static(__dirname + '/html')); //Static path is folder called html
//Also enable EJS template engine:
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/html'); //Set views path to that same html folder
app.set('view engine', 'html'); //Instead of .ejs, look for .html extension
//Start server
app.listen(8000);
//Express routes:
app.get('/', function(req,res) {
res.render('index', { message: 'hello world'});
//this only serves static index.html :(
});
app.get('/home', function(req,res) {
res.render('index', { message: 'hello world'}); //<-- this serves EJS
//whoo-hoo! serves index.html with rendered EJS 'hello world' message
});
This is working perfectly, except for the first route '/' which does not render EJS. All other routes (/home, /about, etc) will conveniently serve the dynamic EJS along with static content. Is there anyway to trick that first '/' to work in the same way?
For Express 3.x try putting router before static:
app.use(app.router);
app.use(express.static(path.join(__dirname, 'html')));
For Express 4.x the router has been deprecated but the concept is the same as routes are like middleware so you should be able to call them before the static middleware.

Why is Express not serving up my static files?

URL: http://example.com:8080/js/file.js
var express = require('express');
app = express();
app.use(express.static('public'));
app.listen(8080);
Directory Structure
/
index.js (loaded node file)
public (folder)
----js (folder)
----file.js (requested file)
Error: Cannot GET /js/file.js
Provide the full path to the directory:
app.use(express.static(__dirname + '/public'));
It might be easier to set up something like what is described in this tutorial
http://www.mfranc.com/node-js/node-js-simple-web-server-with-express/
/* serves all the static files */
app.get(/^(.+)$/, function(req, res){
console.log('static file request : ' + req.params);
res.sendfile( __dirname + req.params[0]);
});
What version of express are you using? For me, using 3.4.0, the following didn't work:
app.use(express.static(__dirname + '/public'));
but this did:
app.use("/public", express.static(__dirname + '/public'));
Not sure if its version specific, but usign the first syntax if was failing with the same Error: Cannot get XXX error

Detect IE in expressjs, but can't get static files

I've tried to detect IE by using expressjs, the code surely redirect me to the error page.
But the problem is that it won't render css files and get image files in my folder.
I think the problem is that expressjs redirect to error_page before the static path is set.
So I put app.all('*', ieRedirecter);, after
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(__dirname + '/uploads'));
The problem is still occur... could someone help me out, thanks!
My settings
function ieRedirecter(req, res, next) {
if(req.headers['user-agent'].indexOf("MSIE") >= 0) {
var myNav = req.headers['user-agent'];
var IEbrowser = parseInt(myNav.split('MSIE')[1])
if(IEbrowser < 9) {
res.render('error/browser_error', {title : 'not supporting your browser'})
} else {
next();
}
} else {
next();
}
};
app.configure(function(){
app.set('port', process.env.PORT || 3000);
...
...
...
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(__dirname + '/uploads'));
app.all('*', ieRedirecter);
})
This order doesn't work:
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(__dirname + '/uploads'));
app.all('*', ieRedirecter);
app.router is the middleware that handles all your routing requests, including app.all(), even though you declare that route after your other middleware (fun fact: at any moment you declare a route – using app.{get,post,all,...} – the app.router middleware is inserted into the middleware chain automatically).
If possible, the easiest solution would be to move the static and IE middleware to before your routes (but I realize that might cause problems with your application setup):
// static middleware first...
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(__dirname + '/uploads'))
// ...followed by the IE check
app.use(ieRedirecter);
// ...followed by your routes
app.get('/', ...);
...
Another solution would be filter out requests for static resources in your ieRedirecter middleware by looking at req.path, but that assumes that you can easily identify those requests (like if they start with /css or /js).

Failed to lookup view in node.js ejs template while the template is only just renamed

I have a node.js application rendering in ejs 3 template.
let 's say -there is one template, course.ejs, it used to work well in node.js.
res.render('course', locals);
However, today when I tried to change the content, let 's say - course.ejs, it doesn't take effect, there is no error with node.js application and the data passed to the template is all right.
I even copy-pasted the content of this template, and make a new template with a different name - course1.ejs. and change my code to
res.render('course1', locals);
then when the app runs again, it pops up a error saying
Error: Failed to lookup view "course1" template.
The code in node.js and template are all right, it is supposed to work in the ways above. Why it doesn't work now. I have my ejs version 0.8.3, while express in 3.1.0 and node.js in 0.10.0
This is my app configuration.
app.configure(function(){
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
app.set('views',__dirname+'/views');
app.use(express.favicon(__dirname + '/public/favicon.ico'));
app.use(express.compress({
filter: function (req, res) {
return /json|text|javascript|css/.test(res.getHeader('Content-Type'));
},
level: 9
}));
app.use(express.bodyParser({uploadDir:__dirname+'/public/uploads',keepExtensions: true,limit: '50mb'}));
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
cookie: { maxAge: 24 * 60 * 60 * 1000 }
,store: sessionStore
,secret: config.sessionSecret
,key: 'express.sid'
,clear_interval: 3600
}));
app.use(express.csrf());
app.use(function(req, res, next){
res.locals.token = req.session._csrf;
next();
});
app.use(express.static(__dirname+'/public'));
}
my static files is in the public folder, and all the templates are in the view folder.
I wonder has anyone met this kind of problem before
I don't think this configuration can work if your templates have the .ejs extension:
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
Using that configuration, Express will look for TEMPLATENAME.html when you call res.render('TEMPLATENAME', ...), and not TEMPLATENAME.ejs. For that, you need this:
app.engine('ejs', require('ejs').renderFile);
app.set('view engine', 'ejs');
So that's the course1 part solved: Express was looking for course1.html, which it couldn't find, so it would generate the error you got (Failed to lookup view...).
However, I don't see how rendering course.ejs could have worked. Perhaps you have another route which is handling the request you're testing? Or you have a course.html in the views folder (besides the course.ejs)?

Resources