The evolution of Azure Functions is getting pretty exciting. The Precompiled functions are easy to create and debug and we can use Attributes to specify the bindings, as apposed to the function.json file.

Issue - Cross Origin Errors

My function was working fine locally and in azure using Postman, until I put one of those pesky browsers in the way and hit the function with JQuery.

My jQuery call was:

 $.ajax({
                            url: url,
                            type: "POST",
                            data: requestData,
                            dataType: "json",
                        })
                        .fail((xhr, status, error) => {
...
                        })
                        .done((result, status, xhr) => {
                            console.log(result);
   ...
                        });

First I had a CORS issue, which gave me an error:

Failed to load https://myfunction.azurewebsites.net/api/functionname?code=abcdefg==: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://myorigin' is therefore not allowed access.

What made it more complicated is that the content-type being received by the function was application/x-www-form-urlencoded so the following entry to deserialise the body failed:

request = await req.Content.ReadAsAsync<Model.IncomingContract>();

with the error "Request failed validation: No MediaTypeFormatter is available to read an object of type 'IncomingContract' from content with media type 'application/x-www-form-urlencoded'."

Reason was in Postman I was setting a header "content-type:application/json".
So I thought great, I'll add that to the ajax call:

$.ajax({
                            url: url,
                            type: "POST",
                            data: JSON.stringify(request),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                        })
...

The thing is, when you set a content type or other non standard headers it triggers the browser to initiate its pre-flight checks, so it did an ORIGIN call.
This failed with the same CORS error.

Resolution

Azure Functions allow you to configure CORS right in the settings in the Azure Portal. I happened to spot it after a bit of investigation.

Select your Azure Function, then on the Overview Tab, click CORS Rules.

To allow all origins, remove all the default items, and add *. Or just add the domains you want.

Click Save and you are good to go.