Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing node request.post with request-promise

I have: I used Node.js request module to get authorization token:

Working code without promise

var request = require('request');
var querystring = require('querystring');

var requestOpts = querystring.stringify({
    client_id: 'Subtitles',
    client_secret: 'X............................s=',
    scope: 'http://api.microsofttranslator.com',
    grant_type: 'client_credentials'
});

request.post({
    encoding: 'utf8',
    url: "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13",
    body: requestOpts
}, function(err, res, body) { //CALLBACK FUNCTION
    var token = JSON.parse(body).access_token;
    amkeAsyncCall(token);
});

I want: It takes some time to get that token. In turn I need makeAsyncCall from getToken callback. So I decide to use a request-promise from here.

Problem: request-promise seems don't work for me at all.

The same (not working) code with promise:

    var rp = require('request-promise');
    var querystring = require('querystring');

    var requestOpts = {
        encoding: 'utf8',
        uri: 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13',
        method: 'POST',
        body: querystring.stringify({
            client_id: 'Subtitles',
            client_secret: 'Xv2Oae6Vki4CnYcSF1SxSSBtO1x4rX47zhLUE/OqVds=',
            scope: 'http://api.microsofttranslator.com',
            grant_type: 'client_credentials'
        })
    };

    rp(requestOpts)
    .then(function() {
        console.log(console.dir);
    })
    .catch(function() {
        console.log(console.dir);
    });
like image 728
VB_ Avatar asked Mar 29 '26 18:03

VB_


1 Answers

I tested your code with the latest version of Request-Promise (0.3.1) and it works fine.

Just the last part of logging to the console was not correct. Use:

rp(requestOpts)
    .then(function(body) {
        console.dir(body);
    })
    .catch(function(reason) {
        console.dir(reason);
    });
like image 103
analog-nico Avatar answered Mar 31 '26 09:03

analog-nico