6

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

1

2 Answers 2

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...

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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... :-)
Did you relaunch your server? Maybe it's running your old code
Got it working finally, just had to correct the path! Thanks for your help! :)
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"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.