Https Post Request with body

Https Post Request with body

本文关键字:body with Request Post Https      更新时间:2023-09-26

我需要从Microsoft AD获得令牌,为此我需要使用BODY进行POST请求。我有这个代码,返回一个缺失的grant_type参数在体的错误。我猜它只是没有发送身体信息。如何配置请求发送正文?

任何帮助将不胜感激!

这是我的代码:

var options = {
    hostname:  'login.microsoftonline.com',
    path: '/common/oauth2/token',           
    method: 'POST',
    headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
    data:{
            grant_type: oauthData.grant_type,
            client_id: oauthData.client_id,
            code: oauthData.code,
            redirect_uri: oauthData.redirect_uri,
            resource: oauthData.resource
         }    
  };
function requestToken(options){
    var req = https.request(options, function(res) {
        console.log("statusCode: ", res.statusCode);
        console.log("headers: ", res.headers);
        res.on('data', function(d) {
            process.stdout.write(d);
        });
    });
    req.end();
    req.on('error', function(e) {
        console.error('---- Error ----');
        console.error(e);
    });
}//end of requestToken()

它没有发送body,因为你没有告诉req对象。

  1. 从选项中删除data{}对象。
  2. 为请求添加request. write()
req.write(qs.stringify({ 
grant_type: 'authorization_code',
client_id: config.clientId,
scope: config.scope,
client_secret: config.clientSecret,
tenant: config.tenant
}))