Home > Software engineering >  How should I request API in express SPA implementation?
How should I request API in express SPA implementation?

Time:04-23

I am implementing SPA using express server.

Server is sending index.html files for all 'get' request in the following way.

app.get("/*", (req, res) => {
  res.sendFile(path.resolve(__dirname, "/public", "index.html"));
});

By the way, what should I do with the get api request as below? I can't get a request because '/*'

app.get("/:id", (req, res) => {
  console.log(req);
});

I think the order is important, so it was the same even if I changed the two and sent the request. Is there a solution?

CodePudding user response:

Distributed architecture

Following the Keep it simple and to have a more clean deployment, I advice you to have the spa and the api on different hosts, domains, git repositories, etc

In real scenarios, your spa will consume multiple APIs, so host the spa within one of them is not the best choice

Check this for more detailed answer

spa api = monolith

Anyway if you need to host the spa inside of api, you need to register the api routes before the static route:

app.get("/:id", (req, res) => {
  console.log(req);
});

app.get("/*", (req, res) => {
  res.sendFile(path.resolve(__dirname, "/public", "index.html"));
});
  • Related