Madhav Sharma
Madhav Sharma

Reputation: 140

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

Upvotes: 1

Views: 667

Answers (2)

julianobrasil
julianobrasil

Reputation: 9377

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 (e.g. http://localhost/index.html), because express won't know the default file to serve:

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

Upvotes: 1

Sravan Kumar
Sravan Kumar

Reputation: 632

Removing this line from app.js works

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

Upvotes: 0

Related Questions