我正在尝试对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
答案 0 :(得分:0)
将该代码粘贴到您的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']}");
}
答案 1 :(得分:0)
AJAX请求必须在same domain之内。 我在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标头进行API调用,以便它不会在浏览器中公开。
答案 2 :(得分:0)
发生这种情况是因为X-RequestDigest
已过期或无效,因此您需要在REST调用之前先调用以下方法
UpdateFormDigest(_spPageContextInfo.webServerRelativeUrl, _spFormDigestRefreshInterval);
Ref:http://sharepointsanjay.blogspot.com/2016/05/how-to-refresh-request-digest-token.html