简体   繁体   中英

How do I allow url string to alter JSON message returned when creating a REST API using express?

I'm relatively new to express and I'm trying to create a locally hosted API that contains my resume. I understand that in a call such as:

app.get("/url", (res, req, next) => {
   res.json({
   //json body
   });
});

the "url" can be used to return a different JSON based upon the html string. However, I'm hoping that there's a way for me to make it so that if the url is just "/", it returns the whole JSON object. Otherwise, if it contains an identifier like: "/experience", then it'll just return a JSON object containing the experience section of the JSON. However, I don't want to copy and paste each section of the JSON for every different possible "GET" call. Does anyone know a way I can do this?

If you have the object, iterate over its keys to make a route for each.

app.get("/", (res) => {
   res.json(theObj);
});
for (const [key, value] of Object.entries(theObj)) {
  app.get("/" + key, (res) => {
    res.json(value);
  });
}

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