简体   繁体   中英

Nodejs routing does not point to all inner routes of Angular App

I am building a frontend application on Angular 9. To serve the application, I am using a NodeJs server to accept all requests and point them to the Dist (Build) files Angular generates.

Problem statement

All routes received by Node server should be forwarded to the Angular Application files.

Problem I'm facing

When I try to use some inner route from the Node server it returns a 404 response. But the page works when I run Angular in development mode.

For example, localhost:4200/innerPage (Angular Dev Server) works but localhost:8000/innerPage (Node Server) does not work.

The Angular page is rendered when I visit localhost:8000 though. Only the internal routes for Angular are not working on the server.

NodeJS code is

const app = express();


app.use("/", express.static(__dirname + "../../dist/TournamentsPlatform/"));

app.listen(8000, () => console.log("Server started on port 8000"));

What I have tried earlier

app.get("/", function (req, res) { res.sendFile(path.join(__dirname + "/../dist/TournamentsPlatform/")); });

app.use("/*", express.static(__dirname + "../../dist/TournamentsPlatform/"));

app.use(express.static(__dirname + "../../dist/TournamentsPlatform/"));

Error - the browser console shows

Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

Misc Info

  • I am using Lazy loading for all Angular routes. Each page is a new module
  • The page works fine when I internally route to it. So, when I go to localhost:8000/ (NodeJS Server) and then click on the link that points to the inner route, it works fine. And at that time, the browser URL is localhost:8000/innerPage

Removing this line from app.js works

app.use(express.static(__dirname + "../../dist/TournamentsPlatform/"));

Try this one:

// fulfill the array with extensions that are part of what an angular
// app must need during load like: .js, .png, .jpg, .woff, .json etc
const allowedExtensions = ['.js'];

app.get('*', (req, res, next) => {
  if (allowedExtensions.some(ext => req.url.includes(ext))) {
    // remove the forward slash at the end of the path 
    const url = req.url.replace(/\/$/,'');
    res.sendFile(path.join(__dirname, 'dist', 'TournamentsPlatform', url));
  } else {
    res.sendFile(path.join(__dirname, 'dist', 'TournamentsPlatform', 'index.html'));
  }
});

BTW, this won't work unless the first request brings index.html explicitly in the path (eg http://localhost/index.html ), because express won't know the default file to serve:

app.get('*', 
  express.static(path.join(__dirname, 'dist', 'TournamentsPlatform'));

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