简体   繁体   中英

Express.js render data from external API

I have a function to get data from an external API:

app.get("/getdata", (req, res) => {
  request.get({
    url: 'http://externalurl',
    json: true
  })
  .pipe(res);
});

It just shows the received JSON object in a browser. The question is, how could I render this data in a template like it's usually done with express methods like res.render("template", {data:data}) so that I could format it?

Assuming your request variable comes from the request npm package , you can use a callback function to receive the response data:

app.get("/getdata", (req, res, next) => {
    request.get("http://externalurl", (err, response, body) => {
        if (err) {
            return next(err);
        }
        res.render("template", {data: JSON.parse(body)});
    });
});

Alternatively, if you're not comfortable with using calllbacks, you can either wrap the request call in a promise or use a ready-made wrapper (please refer to the package's readme for recommendations).

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