简体   繁体   中英

Express routing serves angularjs content but not api

I am using nodejs / express as the server side to my web application.

Another developer no longer working with me merged the angularjs dist bundle with the server application so that running "node index.js" it would serve the angular front end content and the server side api at the same time. It was to improve the slow load.

Since making the nodejs back end serve the ../dist folder front end I have an issue I am trying to resolve around routing.

There is a catch all route that I have current commented out as seen below.

When this is commented out I can hit all the api end points but it will not serve the angularjs content from ../dist folder.

When the catch all route is not commented out it servers up my angular content but cannot reach any of my api endpoints. All calls to the api end points return 200 but never hit the api end points.

在此处输入图片说明

Order matters when defining routes. If your first entry is a catch-all, then it will literally catch everything, even requests to /api . So place your catch-all as the very last entry:

app.get("/api", function(req,res) {
  res.json({
    message: "Hello World!"
  });
});

app.get("*", function(req,res) {
  res.sendFile(__dirname + "/dist/index.html");
});

It's also wise to explicitly declare your SPA route, even if you already have a catch-all:

app.get("/", function(req,res) {
  res.sendFile(__dirname + "/dist/index.html");
});

app.get("/api", function(req,res) {
  res.json({
    message: "Hello World!"
  });
});
app.get("*", function(req,res) {
  res.sendFile(__dirname + "/dist/index.html");
});

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