How to set Express route alias to html file? - node.js

I'm trying to serve some static file with a nicer url endpoints.
For example, /home will serve /public/home.html.
I can probably use res.sendfile() in the route config, but sendfile will not cache the file output in production mode so I am not too sure if this is a good solution.
How do I set routes to act like an alias to a html file?

Try this.
var express = require('express');
var app =express.createServer();
// ------
app.get('/home', function(req,res){
res.sendfile(__dirname + '/public/home.html');
});

There's a module called node-static that provides cacheing functionality. You also might be able to just use symlinks. You might be better served with nginx's try_files or another non-node.js reverse proxy for this functionality.
For a while, there was a staticCache middleware built into express that would do the cacheing. It was removed from connect in January 2014.Here's the github issue where TJ explains staticCache being deprecated.

Related

How to prevent express server from serving api routes from the static folder

Hi I need some help with how express handles routes.
In setting up my express app, I have something like this:
app.use(express.static('public'));
Next, I mount some api routes:
app.use('/api', myrouter);
app.get('*', function(req, res) {
res.sendFile(path.resolve('public/index.html'));
});
But, when the frontend requests data via an api route, e.g. at 'localhost:3000/api/things', I am seeing in the Express debug logs that at some point (unsure when) it actually tries to serve this request as a static file, like:
send stat "C:\myproject\public\api\things" +230ms
Even though this folder doesn't exist in 'public' and should be solely handled by my api. FYI, the handler for /api/things route is only implemented for the GET method, and does get invoked at some point.
How do I stop express server from also trying to serve api requests from the static folder?
Thanks very much.
Answering my own question... which appears to be a duplicate of this one:
`express.static()` keeps routing my files from the route
So the answer is this one: https://stackoverflow.com/a/28143812/8670745
In short, the app.use() declarations that mount your api routers should appear before the app.use() statements which tell express.static where to serve your static files from. This way, the latter acts as a catchall AFTER api route handling is done. Router engine order matters...
Your answer is misinformed, or rather you've misinterpreted the problem. Your original configuration:
app.use(express.static(__dirname + 'public'));
app.use('/api', myrouter);
Looks absolutely fine because there's no clash between the routes. The threads you've linked too aren't really the same, and I can see why moving the routes in those cases would have worked.
The only thing I'd say is your path to your static folder isn't reliable, you should really use path.join, or actually in your case you can just do express.static('public') - express will infer the folder your app is served from.

Serving Angular2 app at a base URL with Express

I have an Angular2 app up and running and a very simple express server. Is it possible to only serve my application when a user visits '/app' (for example)?
If yes how can it be implemented?
I intend to have multiple Angular apps on different URLs and all of these need scripts. Hence a solution which takes care of which script to handle when would be desired.
Edit- Along with the accepted answer, if using the angular-cli, the 'base-href' has to be set to the URL of the app when building the app.
Yes, that's possible.
You have to define that endpoint as the only one:
app.get('/app', function (req, res) {
res.send(/* your application */)
})
You can use this:
// serve the angular web page
app.get('/', app.use(express.static(path.join(__dirname+'/../../public'))));
Note: change the dir name to reach your directory where contains the angular static files.

Express: How to serve font-awesome as static content?

I use express to serve static content on my site and I want to incorporate FontAwesome (npm install font-awesome). However in Font-Awesome's css the links to the font files are appended with a query-string containing versioning information witch express doesn't understand.
Has anyone encountered this and found a fix? Is there a simple way to make express ignore the qs for static content?
var express = require('express')
var app = express()
app.use('/static', express.static('./node_modules/font-awesome/css'))
app.use('/static', express.static('./node_modules/font-awesome/fonts'))
// response 200 | /static/font-awesome.min.css
// error 404 | /static/fontawesome--webfont.woff?v=4.6.3
Update
As #Denys Séguret points our it's not the qs as I had thought. The actual request is for /fonts/fontawesome--webfont.woff?v=...
Solution
app.use('/fonts', express.static('./node_modules/font-awesome/fonts'))
When your browser requests /static/fontawesome--webfont.woff?v=4.6.3, the server is free to ignore the ?v=xxx part. And that's what is done by the express.static module. The point of that part is to prevent browsers and proxies from using an old version of the file.
So the problem isn't where you think it is. The problem is you map the static route to two servers. The first one doesn't find the file and issues a 404.
(Dirty) Solution 1:
Change your mapping
app.use('/static', express.static('./node_modules/font-awesome'))
and change the URLs:
/static/fonts/fontawesome--webfont.woff?v=4.6.3
I say it's dirty because you're serving the unchecked content of a node modules (which is updated when you do a npm update). You should never do that.
 Solution 2:
Create a static directory (the name doesn't matter) and put inside the contents of the ./node_modules/font-awesome/css and ./node_modules/font-awesome/fonts directories then just map it using
app.use('/static', express.static('./static'));

How to mount Ghost on a subdirectory in express

I have a an existing website built with express and I would like to add a "/blog" powered by Ghost. I've added Ghost to my dependencies, installed and configured the urls in Ghosts config to localhost:3000/blog, but now I'm having trouble.
In my app.js I've added the following lines:
var blog = require('./routes/blog');
app.use('/blog', blog);
My blog.js looks like this:
var express = require('express');
var router = express.Router();
var ghost = require('ghost');
ghost().then(function (ghostServer) {
ghostServer.start();
});
router.get('/', ghost);
module.exports = router;
I'm pretty sure blog.js is incorrect.
Node is very limited to do is, for cases when ghost is not configurable as express middleware, which I believe is the case here.
That leaves you with Loadbalancers and DNS as solutions to this problem. On something like HAPRoxy or Nginx you could make those recirects on the /blog route, would need to cater for scripts that the HTML requires to load and to redirect them too.
This might be also better practice since you seperate the concerns.

Express router conflicting with Backbone pushstate

An Express / route serves my Backbone's app index.html.
I'm using pushstate in Backbone but the routes that Backbone should handled are being handled by express, giving 404 responses.
How can I setup Express to serve the index.html but to delegate other routes to Backbone?
In this situation you have multiple options:
You can have a server that handles the same routes as the client does and returns the same results. It is hard to implement but it gives a good url. Github did this.
Always return index.html and handle the route client side. (That is somewhat ugly and hard to maintain)
Don't use pushstate. Amen.
You can use /* approach. Just have it as the last route. That way the other routes such as any service API calls will be matched before the catch all route of /* is matched. This is also how Backbone handles its routes.

Resources