I have an Azure HTTP Trigger with the following code:
namespace MachineLearningHTTPTrigger
{
public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic[] data = JsonConvert.DeserializeObject<dynamic[]>(requestBody);
string area_harvested = data[0].Area_Harvested;
string farmgateprice = data[0].FarmGatePricePHPPSA;
log.LogInformation($"area_harvested: {area_harvested}");
log.LogInformation($"farmgateprice: {farmgateprice}");
// Create response message
var response = new HttpResponseMessage(HttpStatusCode.OK);
var content = new StringContent("Response content");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.Content = content;
return new HttpResponseMessageResult(response);
}
}
public class HttpResponseMessageResult : IActionResult
{
private readonly HttpResponseMessage _response;
public HttpResponseMessageResult(HttpResponseMessage response)
{
_response = response;
}
public async Task ExecuteResultAsync(ActionContext context)
{
var response = context.HttpContext.Response;
response.StatusCode = (int)_response.StatusCode;
foreach (var header in _response.Headers)
{
response.Headers[header.Key] = header.Value.ToArray();
}
if (_response.Content != null)
{
foreach (var header in _response.Content.Headers)
{
response.Headers[header.Key] = header.Value.ToArray();
}
await _response.Content.CopyToAsync(response.Body);
}
}
}
}
It returns the correct Response "Response Content" via Postman. But it does not return the correct Response via Javascript. However, I do confirm that the Javascript does call the HTTP Trigger but just doesnt give the correct response.
here is my javascript
const requestOptions = {
method: "POST",
body: testData,
header: {"Content-Type": "application/json"}
};
try {
const response = await fetch(url, requestOptions);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const responseData = await response.text();
console.log('Response data:', responseData);
} catch (error) {
console.error('There was a problem with the fetch operation:', error);
}