简体   繁体   中英

Angular build served as a static file: problems with routes

I've got a server that holds an Express instance, and a Parse Server built on it. I use that server both as an API, and as a static files server (at least for now; in the future I'll probably split this in two Node instances). The server does not yet have HTTPS enabled, but it indeed has a domain that points to it.

This server is working in a VPS (Virtual Private Server), and is served to the Internet via Nginx. The Nginx configuration file works as following (I substitute the domain name for security reasons):

server {
  listen 80;  server_name mydomain.com;  location / {
    proxy_pass http://localhost:5555;       <--- this is where the node instance is working
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
   }
}

And the Node code that serves the static files:

app.get('/', function(req, res) {
  res.status(200).sendFile(path.join(__dirname, '/public/app/index.html'));
});

The idea here is that when the user accesses to my domain, with no extra parts added to the URL, the server should retrieve the files that are in the public/app folder.

In order to make this work, I had to change the default <base href="/" /> of the www/index.html file, to <base href="/public/app/" /> . That manages to work and correctly serve the web app files if I access to the domain.

The problem is that if I try to access to a specific route defined in Angular, it will fail. Per example, if I access to the domain like www.mydomain.com, I get to the home page and I can perfectly interact with all the features and routes in the app. But if I choose to access to a specific route of the app (ie: www.mydomain.com/user-stats), it won't work and instead, give me an error like this:

Cannot GET /public/app/user-stats

As you see, the server shows the unnecesary /public/app part of the URL which should not appear. I guess I'm understanding something wrong here about either static file serving, or Nginx configuration, or maybe even something with Angular routing itself, but hopefully you can help me here!

Thank you a lot.

Just replace app.get('/', function...) with app.get(function...) and place it at the end of the file. All routes that are not matched previously defined will fallback to this one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM