5

I'm building an Angular app served using Express on Node.

What I'd like to do is when the user visits the site, append their locale to the url (domain.com/en-gb).

Then regardless of what locale they have specified serve up the same index.html.

app.use('/', function(req, res) {
   res.sendFile(__dirname + '/public/index.html');
});

The problem I'm having is working out how to serve up the same file regardless of request, but allowing assets such as images to not be rerouted to index.html as well?

Thanks, Harry

Harry Northover
  • 553
  • 1
  • 6
  • 24
  • Make sure you have a fallback, [there are some unusual locales out there](http://stackoverflow.com/a/3191729/393219) –  Apr 11 '16 at 13:30

2 Answers2

3

If you add a use statement like the following one, you specify the location for your images:

var staticPathImages = __dirname + '/assets/images';
app.use(express.static(staticPathImages));

express will serve those static assets directly, without re-routing to index.html...

MarcoS
  • 17,323
  • 24
  • 96
  • 174
  • I've got it setup like this: var staticPathImages = __dirname + '/public/assets'; app.use(express.static(staticPathImages)); app.use('/', function(req, res) { res.sendFile(__dirname + '/public/index.html'); }); But it's still serving index.html for every file, any idea what I'm doing wrong? – Harry Northover Apr 11 '16 at 13:40
  • The answer is "yes"... :-) Are you sure if you request `localhost:3000/public/assets/image.jpg` (or the like), index.html file is served? It sounds quite strange... I have a setup similar to yours, and it works great... :-) – MarcoS Apr 11 '16 at 13:42
  • Did you relaunch your server? Maybe it's running your old code – krakig Apr 11 '16 at 14:20
  • Got it working finally, just had to correct the path! Thanks for your help! :) – Harry Northover Apr 12 '16 at 09:05
2

MarcoS answer is the correct one, I'll just add a more detailed description :

app.use(express.static(path.join(__dirname, 'public'))); //this line enables the static serving in the public directory

your public directory could be the following :

public 
|_css
|_js
|_images
  |_logo.png

Then, if you want to get an image :

http://localhost:3000/images/logo.png

And if you want to show it in your html page :

<img id="logo" src="/images/logo.png"/>
krakig
  • 1,515
  • 1
  • 19
  • 33