繁体   English   中英

来自 jquery ajax 的 Rest api 调用给出错误 403 Forbidden

[英]Rest api call from jquery ajax gives error 403 Forbidden

我正在尝试对 API 进行简单的 jquery ajax 调用

我的代码:

     jQuery.ajax({
         type: "GET",
         url: "http://example.com/api/v1/testapi",
         headers: { "Authorization": "Basic Ylc5aWXXXXXXlk1ucWx5ZnA=" },
         success: function (data, status) {
             // do something
         },

         error: function (status) {
             // error handler
         }
});

请求头:

OPTIONS /api/v1/testapi HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:40.0) Gecko/20100101 Firefox/40.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://localhost
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization
Connection: keep-alive

响应头:

HTTP/1.1 403 Forbidden
Date: Fri, 28 Aug 2015 10:43:01 GMT
Server: Apache/2.2.15 (CentOS)
X-Powered-By: PHP/5.3.3
Cache-Control: no-cache
access-control-allow-headers: origin, content-type, accept
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, PUT, DELETE
access-control-allow-credentials: 1
X-Debug-Token: 0346f5
Connection: close
Transfer-Encoding: chunked
Content-Type: application/json

Api 与邮递员一起工作,但是当我从 JQuery ajax 调用它时出现错误 403 Forbidden

将该代码粘贴到您的 Web 服务主页上方。

if (isset($_SERVER['HTTP_ORIGIN'])) 
{
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}


if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') 
{
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

}

AJAX 请求必须在同一个域内 我从 Firefox 中尝试了相同的方法,并收到了跨域 AJAX 调用的错误消息。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading 
the remote resource at http://example.com/api/v1/testapi.
(Reason: CORS header 'Access-Control-Allow-Origin' missing)

此外,您似乎正在通过 JS 设置 Authorization 标头。 调用您的服务器会更安全,服务器又通过设置 Authorization 标头来调用 API,这样它就不会在浏览器中公开。

发生这种情况是因为X-RequestDigest已过期或无效,因此您需要在 REST 调用之前调用以下方法

UpdateFormDigest(_spPageContextInfo.webServerRelativeUrl, _spFormDigestRefreshInterval);

参考: http : //sharepointsanjay.blogspot.com/2016/05/how-to-refresh-request-digest-token.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM