如何从Azure移动应用服务中调用HTTP(Azure函数)



我创建了简单的azure函数(http c#),它返回简单的测试。我想从Azure函数返回响应到Azure Mobile Services。现在,我试图调用Azure函数(节点JS)希望从Azure函数中恢复响应。Azure移动服务代码和我简单的Azure功能脚本

   
module.exports = {
     "post": function (req, res, next) {     
          console.log("Started Application Running");   
        var http = require("http");       
        var options = {
          host: "< appname >.azurewebsites.net",         
          path: "api/<functionname>?code=<APIkey>",
          method: "POST",
          headers : {
              "Content-Type":"application/json",
              "Content-Length": { name : "Testing application"}
            }    
        };
        http.request(options, function(response) {
          var str = "";
          response.on("data", function (chunk) {
            str += chunk;
            res.json(response);
            console.log("Something Happens");
          });
          response.on("end", function () {
            console.log(str);             
             res.json(response);
         });          
        });
        console.log("*** Sending name and address in body ***");        
    }
};

这是我的Azure函数

using System.Net;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");
    // parse query parameter
   //string name = req.GetQueryNameValuePairs()
       // .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
        //.Value;
   string name = "divya";
    // Get request body
    dynamic data = await req.Content.ReadAsAsync<object>();
    // Set name to query string or body data
    name = name ?? data?.name;
    return name == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, "Hello Welcome ");
}

。可以帮助我吗?

您应该使用req.write(data)而不是Content-Length发送请求主体。有关如何执行此操作的示例,请参见此答案。

,您的代码应如下所示:

module.exports = {
  "post": function (req, res, next) {       
    var http = require("http");
    var post_data = JSON.stringify({ "name" : "Testing application"});
    var options = {
      host: "<appname>.azurewebsites.net",         
      path: "/api/<functionname>?code=<APIkey>", // don't forget to add '/' before path string 
      method: "POST",
      headers : {
        "Content-Type":"application/json",
        "Content-Length": Buffer.byteLength(post_data)
      }    
    };
    var requset = http.request(options, function(response) {
      var str = "";
      response.on("data", function (chunk) {
        str += chunk;
      });
      response.on("end", function () {
        res.json(str);           
      });          
    });
    requset.write(post_data);
    requset.end();
    requset.on('error', function(e) {
      console.error(e);
    });
  }
}; 

最新更新