node.js https POST 和 body-attributes - 如何?

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

我正在尝试使用我的 node.js 服务器获取令牌。

当有人调用我的服务器的 REST-API 时,将执行下面的代码(在此调用的处理过程中,服务器自己进行了多次调用)。


以下配置适用于 POSTMAN:

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

Header:

Body:


现在我尝试构建此请求的失败代码:

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;    

我没有看到任何错误,我的服务器一直在等待...

您缺少 request.end() 来完成请求。或者作为快捷方式,您可以将单个 request.write(bodyDataString) 更改为 request.end(bodyDataString).