2

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?

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Gives me TypeError: res.render is not a function
My bad. Typed res instead of response in the second line. Thanks for your answer, it solved my problem!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.