使用ExpressJS发帖请求

时间:2014-03-19 15:36:33

标签: node.js express

我需要在我的ExpressJS应用程序上发出一个POST请求...但是我想在回调函数之外获取正文结果以便与它们一起工作......

我想我需要一个同步功能...

var TOKEN;

exports.getToken = function(req, res){

    var postData = {
        client_id: CLIENT_ID,
        client_secret: CLIENT_SECRET,
        grant_type: 'authorization_code',
        redirect_uri: REDIRECT_URI,
        code: CODE
    }

    var url = 'https://api.instagram.com/oauth/access_token';

    // Make my sync POST here and get the TOKEN
    // example :
    // request.post({....}, function(err, res, body){ TOKEN = body; });

    // console.log(TOKEN);

    res.render('index', {title: '****'});
}

1 个答案:

答案 0 :(得分:1)

查看异步库。系列或瀑布功能是你想要的。

https://github.com/caolan/async#waterfall

这些方面的东西:

async.waterfall([
function (callback) {
    var postData = {
        client_id: CLIENT_ID,
        client_secret: CLIENT_SECRET,
        grant_type: 'authorization_code',
        redirect_uri: REDIRECT_URI,
        code: CODE
    }
    var url = 'https://api.instagram.com/oauth/access_token';
    //pass the body into the callback, which will be passed to the next function
    request.post(postData, function (err, res, body) { callback(null,body); });
},
function (token, callback) {
    //do something with token
    console.log(token);
    callback(null);
}
], function (err, result) {
    // result now equals 'done' 
    res.render('index', { title: '****' });
});