Problems with Request using superagent

Asked

Viewed 141 times

2

I’m trying to accomplish a request using the library superagent on my server nodejs, I am following the documentation, however, it is not working. Follow my code nodejs:

var express = require('express');
var app = express();
var request = require('superagent');

app.set('port', (process.env.PORT || 5006));    

request
   .get('http://www.google.com')
   .end(function(err, res){

   });

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

Follow the documentation link for superagent:

http://visionmedia.github.io/superagent/#request-Basics

Could someone help me what I’m missing in this request ?

  • What’s the problem? I tested it and it works well. Put console.log(err, res.text); within that .end(function(err, res){

  • @Sergio, my question is, after receiving the content res.text, instead of exhibiting in the console.log, is it possible to display the requested html page in the browser? Example, in this snippet, I requested the google page through my server nodejs and would like to display it in the browser and not on the console.

  • @Sergio, I got it, I added this piece of code app.get('/', function(req, resp) {
 request
 .get('http://www.google.com')
 .end(function(err, res){
 //console.log(err, res.text);
 enviar = res.text;
 console.log(enviar);
 resp.writeHead(200, { 'Content-Type': 'text/html, application/json; charset=utf-8' });
 resp.end(res.text);
 }); 
});

1 answer

2


You can use it like this:

app.get('/', function(req, resp) {
    request("http://www.google.com", function(err, res){ 
        resp.send(res.body);
    });
});

When you use the resp.send(res.body); Express automatically adds HTTP headers and you don’t need to do it separately.

  • with the body mine didn’t work, with it appears { }. When I use the text appears certain.

  • 1

    @Duds I guess it depends on whether you’re using syntax request().get().end() or passing arguments like I did.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.