Charlie Niekirk
Charlie Niekirk

Reputation: 1143

Cross-Origin Request Blocked Microsoft Azure Function

When trying to call a remote Azure function from my client side, I get this error (URL censored):

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://x.x.com (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

For testing purposes I have set CORS allowed origins in the portal to * as shown below:

enter image description here

This is my client side code:

$.get({
    url: "https://x.x.com",
    crossDomain: true,
    data: {
        weight: weight,
        height: height
    },
    success: function (data) {
        console.log(data);
        alert(data);
    },
    error: function(xhr) {
        console.log("Error");
    }
    });

Could anyone point me in the right direction? Many thanks.

Upvotes: 4

Views: 5948

Answers (2)

Breeno
Breeno

Reputation: 3166

As of January 2019 @Founder's answer didn't work for me - Azure strips out any CORS headers I try to add manually in code. I had to add the desired origins using the CORS settings module. I could see that the Op made reference to this module in his question, but it took me a while to find where it was located. Eventually found it at Function Apps, click your Function app name, go to Platform features tab, then CORS under API over the right-hand side. Not sure why it didn't work for Op, but adding my origins in here worked for me when adding in code would not.

Image showing where to add CORS settings

I did read somewhere that disabling this setting will allow manual adding of CORS headers in code to work, but the setting is enabled by default and I couldn't see any way to disable it (it had 3 Azure domains in there by default, perhaps removing those would disable it...)

Upvotes: 2

Founder
Founder

Reputation: 626

I had to add the origin on the response to get it to work.

When I'm returning the response I call

return Response.CreateResponse(req, HttpStatusCode.OK, result);


public static HttpResponseMessage CreateResponse<T>(HttpRequestMessage req, HttpStatusCode statusCode, T result)
    {
        var response = req.CreateResponse(statusCode, result);
        if (req.Headers.Contains("Origin"))
        {
            var origin = req.Headers.GetValues("Origin").FirstOrDefault();
            response.Headers.Add("Access-Control-Allow-Credentials", "true");
            response.Headers.Add("Access-Control-Allow-Origin", origin);
            response.Headers.Add("Access-Control-Allow-Methods", req.Method +  ", OPTIONS");
        }
        return response;
    }

Upvotes: 1

Related Questions