Microsoft 认知服务 JavaScript 请求"访问控制允许源"



Hy,当我尝试从服务器/本地机器通过JavaScript访问Microsoft Cognitive Services API时,我会出现以下错误。

XMLHttpRequest cannot load http://api.projectoxford.ai/vision/v1.0/analyze?visualFeatures=Categories. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myUrl.com' is therefore not allowed access. The response had HTTP status code 401.

这是我的请求代码:

function requestAPI(){
var params = {
        // Request parameters
        "visualFeatures": "Categories"
};
$.ajax({
        url: "http://api.projectoxford.ai/vision/v1.0/analyze?" + $.param(params),
        beforeSend: function(xhrObj){
            // Request headers
            xhrObj.setRequestHeader("Content-Type","application/json");
            xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{myKey}");
        },
        type: "POST",
        // Request body
        data: "{'url':'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'}",
    })
    .done(function(data) {
        alert("success");
    })
    .fail(function() {
        alert("error");
    });

}

在我的.htaccess中,我已经添加了:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

当我用hurl.it测试请求时,它就起作用了。只是从我的服务器上看没有。

看起来您正在为服务器设置CORS头,这意味着有人可以向您的服务器发出跨域请求。

Microsoft Cognitive Services必须在其服务器上添加这些标头,以便您可以向它们发出跨域请求,或者您必须使用JSONP。

相关内容

最新更新