Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Azure广告发布者';s的授权令牌请求返回302_Javascript_Http_Azure Active Directory_Azure Functions - Fatal编程技术网

Javascript Azure广告发布者';s的授权令牌请求返回302

Javascript Azure广告发布者';s的授权令牌请求返回302,javascript,http,azure-active-directory,azure-functions,Javascript,Http,Azure Active Directory,Azure Functions,在作为我的网页后端的Azure功能中,我根据此指示请求了Azure广告发布者的授权令牌。 这是my Azure功能的代码行: // Stringfy request body const postData = querystring.stringify({ 'grant_type': 'client_credentials', 'client_id': client_id, 'client_secret': client_secret, 'resource

在作为我的网页后端的Azure功能中,我根据此指示请求了Azure广告发布者的授权令牌。 这是my Azure功能的代码行:

  // Stringfy request body
  const postData = querystring.stringify({
    'grant_type': 'client_credentials',
    'client_id': client_id,
    'client_secret': client_secret,
    'resource': resource,
  });

  
  // Initiate options
  var httpAgent = new http.Agent();
  httpAgent.maxSockets = 200;
  const options = {
    hostname: 'login.microsoftonline.com',
    path: `/${tenantId}/oauth2/token`,
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    agent: httpAgent,
  }


  const tokenReq = http.request(options, (res) => {
    console.log(`STATUS: ${res.statusCode}`);
    console.log(`HEADERS: ${JSON.stringify(res.headers)}`);

    res.setEncoding('utf-8')

    res.on('data', (chunk) => {
      console.log(chunk);
      body += chunk;
    });

    res.on('end', () => {
      console.log('No more data in response.');
      console.log("body:" + body);
      context.res = {
        status: 200,
        body: body,
      };
    });
  });

  tokenReq.on('error', (e) => {
    console.log(`problem with request: ${e.message}`);
    context.res = {
      status: 500,
      body: `problem with request: ${e.message}`,
    }
  });


  // write data to request body
  tokenReq.write(postData);
  tokenReq.end();

预期的响应是我需要的访问令牌,但是在本地运行它时,我得到了状态302和一个包含位置和一些其他参数的头作为响应。在我的理解中,状态302表示URL临时移动到标头中提供的位置。现在,我不知道我应该怎么做,我必须发出的请求应该是一个POST请求,这样重定向就不起作用了。我还尝试在收到重定向URL后发出一个新请求,但收到一条错误消息说:getaddrinfo ENOTFOUND{redirect URL from header}。我在这里做错了什么?

302错误是由
http
模块引起的,您使用
require('http')
http.request(选项,(res)…
执行请求,因此显示302错误

我建议您使用
var request=require('request');
来做请求,下面是我的功能代码供您参考(在使用
request
模块之前,您需要先运行
npm install request
来安装它):

module.exports=异步函数(上下文,请求){
log('JavaScript HTTP触发器函数处理了一个请求');
var结果=等待生成肯(上下文);
context.res={
正文:结果
};
}
函数generatetoken(上下文){
var请求=要求(“请求”);
变量选项={
'method':'POST',
“url”:”https://login.microsoftonline.com//oauth2/token',
“标题”:{
“内容类型”:“应用程序/x-www-url-form-urlencoded”
},
表格:{
“客户id”:“xxxxxx”,
“授权类型”:“客户端凭据”,
“资源”:“xxxxx”,
“客户机密”:“xxxxx”
}
};
返回新承诺(功能(解决、拒绝){
请求(选项、功能(错误、恢复){
如果(错误){
拒绝(错误);
}否则{
context.log(res.body);
决议(决议机构);
}
})
})
}
module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    var result = await generatetoken(context);
    context.res = {
        body: result
    };
}

function generatetoken(context){
    var request = require('request');

    var options = {
            'method': 'POST',
            'url': 'https://login.microsoftonline.com/<your tenant id>/oauth2/token',
            'headers': {
            'Content-Type': 'application/x-www-url-form-urlencoded'
        },
        form: {
        'client_id': 'xxxxxx',
        'grant_type': 'client_credentials',
        'resource': 'xxxxx',
        'client_secret': 'xxxxx'
        }
    };

    return new Promise(function(resolve, reject) {
        request(options, function(err, res) {
            if (err) {
                reject(err);
            } else {
                context.log(res.body);
                resolve(res.body);
            }
        })
    })
}