1

I want to do a very simple task, yet I am stuck!

The scenario is like this:

After a get request to my api, I want to http.get from some external site, and then send back the response from this external site to the original api request.

Obviously, the calls are asychronous so the string loremParagraph, doesn't load correctly before sending it back to the api.

Also I get the error: Error: Can't set headers after they are sent.

Here is my code:

module.exports = function(app, express) {

var myLoremRouter = express.Router();

var loremParagraph = '';
//HTTP GET accessed at localhost:8081/mylorem
myLoremRouter.get('/', function(req, res) {

    // Fetch one paragpraphlorem ipsum text from http://www.faux-texte.com/text-random-1.htm
    http.get("http://www.faux-texte.com/text-random-1.html", function(resp) {
            resp.on('data', function(chunk) {
                // console.log('BODY: ' + chunk);
                var $ = cheerio.load(chunk);
                loremParagraph = $('div.Texte').text();
                console.log(loremParagraph);
                // console.log(resp.status);

            });

        })
        // If any error has occured, log error to console
        .on('error', function(e) {
            console.log("Got error: " + e.message);
        });

    //Finally send the result back to the api call
    res.json({ message: loremParagraph });
});

return myLoremRouter;

};

Tasos
  • 57
  • 1
  • 7
  • You're calling `res.json` twice. That's what's giving you the error. You can't modify a response once it's been sent. – Aron Jul 10 '17 at 11:02
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ponury-kostek Jul 10 '17 at 12:04

1 Answers1

1

Try this. Here chunks are added till we are ready to use the complete data.

https://stackoverflow.com/a/21953201/6219247

myLoremRouter.get('/', function(req, res) {
    var body = '';
    http.get({
        host: 'www.faux-texte.com',
        port: 80,
        path: '/text-random-1.html'
    }, function(resp) {
        resp.on('data', function(chunk) {
            body += chunk;
        });
        resp.on('end', function(chunk) {
            var $ = cheerio.load(body);
            loremParagraph = $('div.Texte').text();
            res.json({ message: loremParagraph });
        });
    })
    .on('error', function(e) {
        // handle/send error
        res.send(/*...*/);
    });
});
codesome
  • 81
  • 5