Search code examples
node.jsoauth-2.0httprequestnode-rest-clientnode-https

node.js https POST with body-attributes - HOW?


I am trying to get a Token with my node.js server.

The code below gets executed when someone calls the REST-API of my server (within the processing of this call the server makes several calls himself).


The following configuration works in POSTMAN:

URL: https://login.windows.net/MyCompanyTenant.onmicrosoft.com/oauth2/token

Header:

  • Cache-Control: no-cache
  • Content-Type: application/x-www-form-urlencoded

Body:


Now My failing Code trying to build this Request:

function retrieveAuthToken() {
    var deferred = q.defer();   

    var bodyDataString = querystring.stringify({
        grant_type: "password",
        client_id:  someClientId, 
        resource: someUrl,
        username: someUsername,
        password: someUsernamePassword,        
        client_secret: someString
   });
   //I also tried replacing thie bodyDataString by the bodyString from the working request provided by Fiddler

    var options = {
        host: 'login.windows.net',
        path: '/someTenant/oauth2/token',
        method: 'POST',
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Cache-Control": "no-cache"
        }
    };  

    var request = https.request(options, function(response){
        var body = '';
        response.on('data', function(d) {
            body += d;
        });
        response.on('end', function() {
            var parsed = JSON.parse(body); //todo: try/catch
            rdeferred.resolve(parsed.access_token);
        });               
    });

    request.on('error', function(e) {
        console.log(e.message);
        deferred.reject();
    });

   request.write(bodyDataString ); 
   return deferred.promise;    

I dont see any error, my server just waits and waits...


Solution

  • You're missing a request.end() to finish the request. Or as a shortcut, you can change the single request.write(bodyDataString) to request.end(bodyDataString).