3

Newbie to nodejs. I have a an API folder - whenever the server get an API request - it should execute the function binded to that route. However - whenever there is a non-API request, I want the nodejs server serve the static files so that the angular app will "take responsibility" and show the relevant components. This is mainly reflected when I do a refresh (F5) when I'm in one of the angular component.

Here is my nodejs relevant code:

app.use("/api", require("./api/v1"));  // This should take care in every API request

My static files located (after deploy) under /site/public/dist/public/ and there is an index.html there with a <base href="<app root location>">. To make things simple - I would like my application (after build to prod) to manage to make a refresh and reach the same component without the "cannot get" error

This is what I've already tried to do, not much of success:

app.use('/', express.static(__dirname +'/site/public/dist/public/', { redirect: false }));
app.use('*', (req, res) => 
{
  res.sendFile(__dirname +'/site/public/dist/public/');
 });
imran ali
  • 383
  • 1
  • 13
Guy E
  • 1,775
  • 2
  • 27
  • 55

2 Answers2

4

You need to add index.html in order to show the html file

Try using something like this

// For static files
app.use(express.static('%dir_name relative to the file path%'))
// For virtual routes use 
app.use('*', (req, res) => 
{
  res.sendFile(__dirname +'/site/public/dist/public/index.html');
 });

Ref https://expressjs.com/en/starter/static-files.html

Dhruv
  • 121
  • 7
0

Probably it's too late but perhaps it could help someone else. If you want to publish static content without losing the URL routing you already have (ie. An Angular application which is probably using the RouterModule module).

Then you should define a GET method with the '*' wildcard, and then filter the requests in order to identify if it's looking for static content.

or if it's looking for a specific sub-route in your client application (in which case it should return the index.html file), so your method should be something like this:

  router.get('*', (req, res) => {
    var pattern = new RegExp('(.css|.html|.js|.ico|.jpg|.jpeg|.png)+$', 'gi');
    if (pattern.test(req.url)) {
      res.sendFile(path.resolve(__dirname, `../../public${req.url}`));
    } else {
      res.sendFile(path.resolve(__dirname, '../../public/index.html'));
    }
  });
Ali Asgher Badshah
  • 811
  • 1
  • 11
  • 34