简体   繁体   中英

How to pass res from one function to another?

FB.api('4', function (res) {
  if(!res || res.error) {
   console.log(!res ? 'error occurred' : res.error);
   return;
  }
  console.log(res.id);
  console.log(res.name);
});

// viewed at http://localhost:8080
app.get('/test', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));

});

Ive created this small FB.api call which return some data. Now I want to display this data when accessing localhost:8080/test, how do I do that? what is the way to do stuff like that? Can someone point me to some documentation of possible?

First you add your FB.api call inside an express route like this

app.get('/something', function(req, res) {
    FB.api('4', function (result) {
        if(!res || res.error) {
            return res.send(500, 'error');
        }

        res.send(result);
    });
});

Then inside index.html you can add some javascript to your page and create an XHR to call 'localhost:8080/something' like that

index.html

<script type="text/javascript">
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://localhost:8080/something');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            var data = xhr.responseText;

            //Do whatever you want with this data.
        }
    }
    xhr.send();
</script>

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