1

嗨,当我尝试从我的服务器/本地计算机通过 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 测试请求时,它可以工作。只是从我的服务器它没有。

4

1 回答 1

1

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

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

于 2016-04-09T12:28:19.577 回答