【问题标题】:Azure Function ignoring https.requestAzure 函数忽略 https.request
【发布时间】:2019-05-07 12:22:10
【问题描述】:

这行代码我有一个天蓝色的功能。

var myReq = https.request(options, function(res) {
            context.log('STATUS: ' + res.statusCode);
            context.log('HEADERS: ' + JSON.stringify(res.headers));
            body += res.statusCode
            res.on('data', function (chunk) {
                context.log('BODY: ' + chunk);
            });
        });

        myReq.on('error', function(e) {
            context.log('problem with request: ' + e.message);
        });

        myReq.write(postData);
        myReq.end();

但我的代码似乎只是跳过了这部分代码,没有错误。我是 Azure 和 node.js 的新手,所以我可能错过了设置它的一些基本部分。

有什么想法吗?

编辑: 这是我的完整代码

const https = require('https');
const querystring = require('querystring');

module.exports = async function (context, req) {

    if (req.query.accessCode || (req.body && req.body.accessCode)) {
        context.log('JavaScript HTTP trigger function processed a request.');
        var options = {
            host: 'httpbin.org',
            port: 80,
            path: '/post',
            method: 'POST'
        };

        var postData = querystring.stringify({
            client_id : '1234',
            client_secret: 'xyz',
            code: req.query.accessCode
        });

        var body = "";
        var myReq = https.request(options, function(res) {
            context.log('STATUS: ' + res.statusCode);
            context.log('HEADERS: ' + JSON.stringify(res.headers));
            body += res.statusCode
            res.on('data', function (chunk) {
                context.log('BODY: ' + chunk);
            });
        });

        myReq.on('error', function(e) {
            context.log('problem with request: ' + e.message);
        });

        myReq.write(postData);
        myReq.end();
        context.log("help");
        context.res = {
            status: 200,
            body: "Hello " + (body)
        };
    } else {
       context.res = {
            status: 400,
           body: "Please pass a name on the query string or in the request body"
      };
    }
};

【问题讨论】:

  • 很可能您只需要等待您的请求响应。
  • 我必须在哪里等待?我试过var myReq = await https.request(options, function(res) {...,但什么也没发生。 @CarlosAlvesJorge

标签: node.js azure azure-functions


【解决方案1】:

理想情况下它应该可以工作。您也可以尝试使用如下的请求模块

const request = require('request');
request('http://www.google.com', function (error, response, body) {
  console.error('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

试试看是否有帮助。

【讨论】:

  • 这会在 azure 中出现错误,Exception: Error: Cannot find module 'request'
【解决方案2】:

通过正确地等待来解决。以this 为指导。

var https = require('https');
var util = require('util');
const querystring = require('querystring');
var request = require('request')

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    /*if (req.query.name || (req.body && req.body.name)) {*/
    var getOptions = {
        contentType: 'application/json',
        headers: {
            'Authorization': <bearer_token>
         },
    };
    var postData = {
        "key": "value"
    };
    var postOptions = {
        method: 'post',
        body: postData,
        json: true,
        url: <post_url>,
        headers: {
            'Authorization': <bearer_token>
         },
    };
    try{
        var httpPost = await HttpPostFunction(context, postOptions);
        var httpGet = await HttpGetFunction(context, <get_url>, getOptions);
        return {
            res: httpPost
        };
    }catch(err){
       //handle errr
       console.log(err);
    };
};

async function HttpPostFunction(context, options) {
    context.log("Starting HTTP Post Call");
    return new Promise((resolve, reject) => {
        var data = '';
        request(options, function (err, res, body) {
            if (err) {
              console.error('error posting json: ', err)
              reject(err)
            }
            var headers = res.headers;
            var statusCode = res.statusCode;
            //context.log('headers: ', headers);
            //context.log('statusCode: ', statusCode);
            //context.log('body: ', body);
            resolve(body);
          })
    });
};

async function HttpGetFunction(context, url, options) {
    context.log("Starting HTTP Get Call");
    return new Promise((resolve, reject) => {
        var data = '';
        https.get(url, options, (resp) => {
            // A chunk of data has been recieved.
            resp.on('data', (chunk) => {
                data += chunk;
            })
            // The whole response has been received. Print out the result.
            resp.on('end', () => {
                resolve(JSON.parse(data));
            });
        }).on("error", (err) => {
            console.log("Error: " + err.message);
            reject(err.message);
        });
    });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2012-06-08
    • 1970-01-01
    相关资源
    最近更新 更多