Cross-Origin Request Blocked Microsoft Azure Function

左心房为你撑大大i 提交于 2021-01-27 16:47:42

问题


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:

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.


回答1:


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



回答2:


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.

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...)



来源:https://stackoverflow.com/questions/48503686/cross-origin-request-blocked-microsoft-azure-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!