无法获得 401 响应 body
Can't get 401 response body
我使用 jQuery.ajax()
设法获得了 JSON 内容。目前,它从包含单个 index.php 文件的另一台主机获取内容,返回带有以下 body 的 401 响应:{'status':401}
.
这是JS:
$(document).ready(function() {
$.ajax({
url: 'http://restapi',
type: 'GET',
dataType: 'json',
success: function() { document.write('works'); },
error: function(xhr) { document.write('failed, status:' + xhr.status); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer 12345');
}
和 PHP:
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Headers: X-Requested-With, Authorization");
header("HTTP/1.1 401 Unauthorized");
echo json_encode(['status' => 401]);
exit;
如果我删除 header、xhr.setRequestHeader('Authorization', 'Bearer 12345');
,一切正常(响应有 json body 和 xhr.status
returns 401
)。但是有了授权 header body returns 什么都没有 xhr.status
returns 0
.
我需要在 header 中发送身份验证令牌。
我使用 Node.js 做了同样的事情,并注意到它发送了两个 requests/responses。一个带有 204 header,另一个带有预期的 401 和 json body。第一种方法是 OPTIONS,第二种方法是 GET,所以我用这个试了一下:
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("HTTP/1.1 204 No Content");
} else {
header("HTTP/1.1 401 Unauthorized");
echo json_encode(['status' => 401]);
}
工作正常。
我使用 jQuery.ajax()
设法获得了 JSON 内容。目前,它从包含单个 index.php 文件的另一台主机获取内容,返回带有以下 body 的 401 响应:{'status':401}
.
这是JS:
$(document).ready(function() {
$.ajax({
url: 'http://restapi',
type: 'GET',
dataType: 'json',
success: function() { document.write('works'); },
error: function(xhr) { document.write('failed, status:' + xhr.status); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer 12345');
}
和 PHP:
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Headers: X-Requested-With, Authorization");
header("HTTP/1.1 401 Unauthorized");
echo json_encode(['status' => 401]);
exit;
如果我删除 header、xhr.setRequestHeader('Authorization', 'Bearer 12345');
,一切正常(响应有 json body 和 xhr.status
returns 401
)。但是有了授权 header body returns 什么都没有 xhr.status
returns 0
.
我需要在 header 中发送身份验证令牌。
我使用 Node.js 做了同样的事情,并注意到它发送了两个 requests/responses。一个带有 204 header,另一个带有预期的 401 和 json body。第一种方法是 OPTIONS,第二种方法是 GET,所以我用这个试了一下:
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("HTTP/1.1 204 No Content");
} else {
header("HTTP/1.1 401 Unauthorized");
echo json_encode(['status' => 401]);
}
工作正常。