gpt4 book ai didi

javascript - 如何从Azure移动应用服务调用HTTP(Azure Functions)?

转载 作者:行者123 更新时间:2023-12-03 03:32:48 25 4
gpt4 key购买 nike

我创建了简单的 azure 函数 (Http+C#),它返回简单的测试。我想将 azure 函数的响应返回到 azure 移动服务。在我从移动服务调用存储过程之前。现在我正在尝试调用该函数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。请参阅this answer有关如何执行此操作的示例。

您的代码应如下所示:

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);
});

}
};

关于javascript - 如何从Azure移动应用服务调用HTTP(Azure Functions)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46011917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com