HTTP Trigger Not Returning Response to Javascript

Ziggy Zulueta 490 Reputation points MVP
2023-02-27T18:26:51.07+00:00

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);
    }
Not Monitored
Not Monitored
Tag not monitored by Microsoft.
37,798 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Ziggy Zulueta 490 Reputation points MVP
    2023-03-13T01:05:54.09+00:00

    It is apparently an issue with the Microsoft end.. specifically the CORS setting in the Azure API Management Service.

    To solve do the following:

    1. Go to the API and click design
    2. Look for Inbound Processing and click Add Policy->CORS
      CORS
    3. Then in CORS setting under allowed origins add your website. In this case I was testing first with codepen so the website is cdpn.io. Capture
    0 comments No comments