mikebrsv
mikebrsv

Reputation: 1960

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?

Upvotes: 2

Views: 4236

Answers (1)

mingos
mingos

Reputation: 24502

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).

Upvotes: 4

Related Questions