如何在NodeJS中使用Express进行GET请求内部的GET请求

4

基本上,我正在尝试从Facebook在我的回调GET方法中获取访问令牌。以下是我的代码。

getAccessToken根本没有被调用。实现它的正确方式是什么?

app.get('/fbcallback', function(req, res) {


  var code = req.query.code;

  var getAccessToken =  'https://graph.facebook.com/v2.12/oauth/access_token?'+
   'client_id='+client_id+
   '&redirect_uri='+redirect_uri+
   '&client_secret='+client_secret+
   '&code='+code;


   app.use(getAccessToken, function(req, res) {

        console.log('Token Call');

   });


});

尝试从请求体中获取参数,例如req.body.code。 - Xay
在控制台中显示你遇到的错误。 - Nikhil Savaliya
1
这看起来很奇怪...为什么在app.get中使用app.use?你应该查看文档:http://expressjs.com/de/guide/using-middleware.html - andyrandy
不应该在get调用内使用app.use。它是用于中间件的。 - Rahul Sharma
也许你可以尝试使用 request 模块,作为一个 HTTP 客户端来处理? - Felix Fong
1个回答

6

在get调用内部,不应使用app.use

您必须要做的是像下面这样。在get调用内部,为获取令牌进行另一个get调用。

var request = require('request');

app.get('/fbcallback', function (req, res) {
    var code = req.query.code;
    var getAccessToken = 'https://graph.facebook.com/v2.12/oauth/access_token?' +
        'client_id=' + client_id +
        '&redirect_uri=' + redirect_uri +
        '&client_secret=' + client_secret +
        '&code=' + code;

    request(getAccessToken, function (error, response, body) {
        console.log('error:', error); // Print the error if one occurred
        console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
        console.log('body:', body); // Print the HTML for the Google homepage.
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接