跨域请求阻止了Microsoft Azure功能 [英] Cross-Origin Request Blocked Microsoft Azure Function

查看:51
本文介绍了跨域请求阻止了Microsoft Azure功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试从客户端调用远程Azure函数时,出现此错误(经过URL审查):

跨域请求被阻止:相同来源策略"不允许读取

这是我的客户端代码:

  $.get({网址:"https://x.x.com",crossDomain:是的,数据: {重量:高度:高度},成功:功能(数据){console.log(data);警报(数据);},错误:function(xhr){console.log(错误");}}); 

有人能指出我正确的方向吗?非常感谢.

解决方案

我必须在响应中添加原点才能使其正常工作.

当我返回响应时,我会打电话

 返回Response.CreateResponse(req,HttpStatusCode.OK,结果);公共静态HttpResponseMessage CreateResponse< T>(HttpRequestMessage请求,HttpStatusCode statusCode,T结果){var response = req.CreateResponse(statusCode,result);如果(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",来源);response.Headers.Add("Access-Control-Allow-Methods",req.Method +,OPTIONS");}返回响应;} 

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.

解决方案

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

这篇关于跨域请求阻止了Microsoft Azure功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆