PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] How should I request API in express SPA implementation?

 October 13, 2022     axios, express, javascript, single-page-application     No comments   

Issue

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?


Solution

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

  • https://stackoverflow.com/a/71791940/3957754

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"));
});


Answered By - JRichardsz
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing