如何将res从一个函数传递给另一个函数?

时间:2016-10-29 17:43:05

标签: javascript node.js

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'));

});

我创建了这个小FB.api调用,它返回一些数据。现在我想在访问localhost:8080 / test时显示这些数据,我该怎么做?这样做的方法是什么?有人能指出一些可能的文件吗?

1 个答案:

答案 0 :(得分:2)

首先,在像这样的快递路线中添加你的FB.api电话

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

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

然后在index.html中你可以添加一些javascript到你的页面并创建一个XHR来调用' localhost:8080 / something'像那样

<强>的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>
相关问题