无法获得401响应正文 [英] Can't get 401 response body
问题描述
我设法使用 jQuery.ajax()
来获得JSON的内容。目前,它将从另一台主机包含一个单一的index.php文件返回401响应,其内容体内容: {状态:401}
I managed to get JSON content using jQuery.ajax()
. Currently, it fetches the content from another host containing a single index.php file returning a 401 response with the following body: {'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;
如果我删除标题, xhr.setRequestHeader('授权','承载12345');
,一切工作正常(响应有一个JSON的身体和 xhr.status
返回 401
)。但随着Authorization头身返回任何内容并 xhr.status
返回 0
。
If I remove the header, xhr.setRequestHeader('Authorization', 'Bearer 12345');
, everything works fine (the response has a json body and xhr.status
returns 401
). But with the Authorization header the body returns nothing and xhr.status
returns 0
.
我需要发送的身份验证令牌在这头。
I need to send the auth token in that header.
推荐答案
我在使用Node.js的同样的事情,发现它派了两个请求/响应。一个具有204头和另一个与预期401和JSON体。第一种方法是OPTIONS和第二个方法是GET,所以我想用这样的:
I made the same thing using Node.js and noticed it sent two requests/responses. One with a 204 header and another with the intended 401 and the json body. First method was OPTIONS and second method was GET, so I tried it with this:
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("HTTP/1.1 204 No Content");
} else {
header("HTTP/1.1 401 Unauthorized");
echo json_encode(['status' => 401]);
}
工作正常。
这篇关于无法获得401响应正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!