NodeJS and Express: Add auth middleware to static path - node.js

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

Related

is is possible to extract express use into another file?

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

EJS file not loading after using express.static

I have some plain HTML/CSS files in my frontend folder and the ejs files in the views folder and every other ejs file loads perfectly but the index.ejs file
I don't know what I am doing wrong here
This is my server.js: (this is a basic version of my server file)
const app = express();
app.set('views', __dirname + '/views');
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/frontend"));
app.get("/", (req, res) => {
res.render("index");
});
//The below file loads perfectly. (requireAuth is a authentication middleware)
app.get("/create", requireAuth, (req, res) => {
res.render("create");
});
Also both the files index.ejs and create.ejs are very similar
If anyone requires any extra details then they can comment down.
You've defined static middleware for / (root path) and the index page is also defined for root path, but because static middleware is defined early, express tries to find and return static file instead of rendering index page.
You have two variants here:
Define static middleware for some path different than root:
app.use("/public", express.static(__dirname + "/frontend"));
Don't use root path for index page: app.get("/index", (req, res)...

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

Express 3 - Serving static scripts/styles - Error: Failes to load resource (404)

I am new to node and server-side development in general and started having a look at it today so mind my question. I have looked for suiting answers in previous post, yet somehow every suggested solution was criticized by many users.
I can't serve static scripts/styles due to the following error:
Failed to load resource: the server responded with a status of 404 (Not Found)
I am using express 3.1.0.
Here is my code:
app.js
var express = require('express');
var app = express();
var routes = require('./routes');
app.configure(function () {
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));
});
app.get('/', routes.home);
app.get('/about', routes.about);
app.get('/blog', routes.blog);
app.get('/faq', routes.faq);
app.get('/terms', routes.terms);
app.get('/privacy', routes.privacy);
app.get('/jobs', routes.jobs);
app.get('/press', routes.press);
app.listen(8080);
index.js (routes)
exports.home = function(req, res){
res.render('home', { title: "Home"});
};
exports.about = function(req, res){
res.render('about', { title: "About" });
};
etc...
layout.jade
doctype 5
html
head
title= title
link(rel='stylesheet', href='public/styles/bootstrap.css')
body
block content
br
a(href='../') Home
br
a(href='../about') About
br
etc...
home.jade
extends layout
block content
p Home
When you setup server middlewere it looks for requests at the root unless specified otherwise if you are looking for a stylesheet in "public/styles" you request it at just "/styles"
to make the middlewere answer to requests to /public change it to
app.use('/public', express.static(__dirname + '/public'));
I tried using
app.use('/public', express.static(__dirname + '/public'));
instead of
app.use(express.static(__dirname + '/public'));
and it worked.
However according to the first answer in this post: express.js not serving my image it is not considered good. I can't understand why? And what else would be a better solution?

node.js/express: Sending static files if they exist

I want to serve html files from a folder if they exist, otherwise fallback to the dynamic app.
currently I use something like:
var express = require('express');
var app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(4444);
app.use("/", express.static(__dirname + '/../WebContent/index.html'));
app.use("/styles", express.static(__dirname + '/../WebContent/styles'));
app.use("/script", express.static(__dirname + '/../WebContent/script'));
//here I would like to define a rule like this:
//app.use("*.html", express.static(__dirname + '/../WebContent/*html'));
How can I achieve this?
Some tutorials use a module called connect. If it's the most elegant solution to my problem, how can I integrate connect to my current code?
You don't have to do anything special.
i'm assuming the WebContent folder is in the root.
And if all your static content are in the same base folder like you've shown, you don't have to specify it multiple times.
app.use(express.static(__dirname + '/WebContent'));
if you have a file called file.html in the WebContent folder you can now access it via the url i.e. localhost:4444/file.html
You are using a lot of boilerplate. It is easier using routes. Here is an example:
var routes = require('./routes');
app.configure(function () {
...
app.use(express['static'](path.join(__dirname, '/../WebContent')));
app.use(app.router);
});
// Routes
app.get('/', routes.index);
routes/index.js:
exports.index = function (req, res) {
res.render('index');
};
Rendering your webapp root outside your project root is very strange. Feels like bad practice. Is this necessary?

Resources