exclude a folder from expressjs routing - javascript

On my expressjs app, public assets are loaded in this way:
app.use(express.static(__dirname + '/public'));
And then I redirect all requests to the index, to handle every path with Backbone
app.get('*', routes.index);
Why the /public folder is redirect too?
Also if i try to add '/public' as a first argument, it doesn't work:
app.use('/public', express.static(__dirname + '/public'));

For anyone who get any problem related to static files serving:
Before evaluating possible solutions to the problem, be sure to define express.static before the app.use(app.router).
I found lots of examples online: sometimes its defined below, sometimes not.
Putting it first solved all my problems.
app.use(express.static(path.join(__dirname + '/public')))
app.use(app.router)

After you placed the static router before app.router, express will attempt to serve requests first by matching a file from the static folder (public), if there's no match, it will pass it to routes.index as the following rule matches everything;
app.get('*', routes.index);
Also, to match any file from public dir, you need not use /public/ in the request url.
For example to fetch public/images/icon.png or public/js/scripts.js, you will only need to access /images/icon.png or /js/scripts.js. If you invoke a /public request, it will not match anything in static dir, and pass the request on to routes.index.
Hope it helps.

Related

Having all website paths load the same static website in express

In my express server, I want to have all paths load the same static website, which I tried doing with the following code:
const express = require('express');
const app = express();
app.use('*', express.static('build'));
app.listen(3000);
Unfortunately I am presented with the following console errors when I navigate to any path on localhost:
:3000/main.js/:1 Uncaught SyntaxError: Unexpected token <
When attempting to view the JS file with the error, it seems to be serving index.html in its place.
I know this is due to the wildcard, but I can't think of a way to cleanly exclude all file names and paths from the static server.
I think you're looking for something a little more like this..app.use(express.static('public')
if your tree looks like
ProjectName
| server.js
| public
| index.html
you don't need the * as a parameter since setting the express.static sets the folder open to public view. This is how you separate your server code and client code. Be careful not to expose your entire project directory as people will then have access to your server code. This is why you're client files should be kept in a public folder or a www folder (common practices)
--EDIT
//this will server css, and js files so they can be linked into the html
app.use(express.static(__dirname + '/public'));
//this will force all url's except the public files to be given the index.html file.
app.use('*', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});

Express Nodejs: Static Files Multiple Directories. One of them only allowing .png requests

My goal in my NodeJS Express app is to have 2 static directories.
Every file in the first directory (/client) is accessible.
Only .png files in the second directory (/quest) are accessible.
This is what I tried to do:
app.use(/\/quest\/.*\.png/,express.static('quest')); //doesnt work
app.use(express.static('client')); //works correctly
//Note: This will actually trigger the messages
app.use(/\/quest\/.*\.png/,function(){
console.log(100);
});
But it doesn't work...
I'm not entirely sure why but app.use syntax for some reason only matches the route, it doesn't set the req.url to the requested URL which is required by express.static to look for the specified file. app.VERB syntax is better suited to handle routes.
Then since you're already telling express.static to look into /quest directory, you need to strip that from the req.url or otherwise it'll look for /quest /quest/file.png
app.get('/quest/*.png', function(req, res, next) {
req.url = req.url.replace('/quest','');
next();
}, express.static('quest'));
Verified that laggingreflex's solution works on express 4.13.0

Troubleshooting node.js error

I just inherited a node.js project, where I'm suspicious that some of the original boilerplate necessary for a node project hasn't been finished. This is also my first time using node.js.
Anyway, when I run node app.js, the correct port boots up and everything, but the app can't load a number of the script files (the error "Uncaught SyntaxError: Unexpected token <" is given on each js file unable to be loaded). I've tried to troubleshoot this error, there are a lot of resources online for it, but I haven't been able to nail it down. I tried adding type="text/javascript" to each of the script tabs but it didn't change anything.
When I click to troubleshoot the incorrect loading paths of the scripts, they all bring me to the index.html page. Thus, for some reason, it seems like this section of the code from the app.js file isn't working:
// serve all asset files from necessary directories
app.use('/js', express.static(__dirname + '/public/js'));
app.use('/css', express.static(__dirname + '/public/css'));
app.use('/partials', express.static(__dirname + '/public/partials'));
app.use('/lib', express.static(__dirname + '/public/lib'));
// JSON API
app.get('/api/name', api.name);
// redirect all others to the index (HTML5 history)
app.all('/*', function(req, res, next) {
res.sendfile('index.html', { root: __dirname + '/public' });
});
However, it looks like it should be working properly (following the paths of the files). Any ideas?
Almost certainly the app.all route is sending back HTML for a request that should be sending javascript. You need to look at the specific URLs that the browser is fetching as script tags but the server is sending back HTML. The corresponding .js files probably are just not there under public/js which causes the router to proceed to the catch-all route.
Side note you can compress your express.static routes to just this because of how your URLs line up with the filesystem structure.
// serve all asset files from necessary directories
app.use(express.static(__dirname + '/public'));

Passport.js express views

I'm using passport and some static .html files. I want to include them as express views or static files. Now I want SOME .html files like login.html to be available for everyone, but the other view files like secret.html should need passport.
I know, that you can use
app.get('somePath', ensureAuthenticated, function (req, res, next) {} for routes, but I want it for static files.
How to do it on a non-hacky way?
If all "secure" files share a distinct URL prefix, such as /public/secure, you can use() ensureAuthenticated with this path:
app.use('/public/secure', ensureAuthenticated);
app.use('/public', express.static(__dirname + '/public'));
Otherwise, the express.static() middleware doesn't offer many options for controlling access. For the most part, it assumes all available files from the path given to it are meant to be "public."
Though, it does normally refuse to send hidden files, following the *nix standard of a . prefix:
~/path/to/.secret.html
Then, to actual serve it, you can send the file yourself in the route you suggested with the middlware attached:
app.get('/path/to/secret.html', ensureAuthenticated, function (req, res) {
res.sendfile(__dirname + '/path/to/.secret.html');
});
And, you may want to consider moving it out of your static() directory,

In express router method is not working if i serve static files

In my node application first i want to serve my static files and then using router method depending upon the incoming request i will query the DB and get the body of the html page then i will send this body content to the client side and finally using Backbone.js i will render this body in my html page.Now what is my problem means express router method is not working if i serve static files.But if i remove the below line means my router is working.
app.use(express.static(__dirname + '/public'));
app.js
var express=require('express');
var app=express();
app.use(express.static(__dirname + '/public'));
app.get('/',function(req,res){
console.log('router called successfully...');
res.send('body of the page');
res.end();
});
app.listen(8011);
app.use(express.static(__dirname + '/public'));
Your unnecessary anonymous function is screwing up how the middleware is supposed to work. The above line is in 95% or more of all express sample apps. Not sure why you decided to deviate from that, but your version is a useless middleware that creates a static middleware and immediately discards it.

Categories

Resources