API访问控制检查

时间:2018-02-02 16:43:08

标签: javascript ajax api http

我在我的应用中从Javascript访问外部API,我收到此错误:

无法加载http://www.myapp.com//api/v1/syndication/categories?output=json:对预检请求的响应未通过访问控制检查:否' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' http://local.myapp.com'因此不允许访问。响应的HTTP状态代码为400。

    function MakeAPIRequest(requestUrl, requestData, callback) {

    $.ajax({

        beforeSend: function(xhr){
            xhr.setRequestHeader('Access-Control-Allow-Origin', 'http://local.myapp.com'); 
            xhr.setRequestHeader('Token', apiKey); 
        },
        type: "GET",
        url: requestUrl,
        data: requestData,
        dataType: "json",
        success: function(json){
            callback(json);
        }

    });

}

API可能不接受" OPTIONS"请求? 这是服务器响应:

{"错误":"错误请求 - 仅接受获取请求","代码":1009}

2 个答案:

答案 0 :(得分:1)

{"error":"Bad Request - Only accepts get requests","code":1009}告诉您服务器只接受GET次请求,而No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://local.myapp.com' is therefore not allowed access.是所谓的cors错误。

您需要允许服务器上的CORS摆脱此错误。

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

答案 1 :(得分:0)

这是一个CORS问题,您调用的API位于不同的域中,访问控制标头不允许来自其他域的请求。