gpt4 book ai didi

javascript - 无法获取 401 响应正文

转载 作者:行者123 更新时间:2023-11-28 00:01:38 28 4
gpt4 key购买 nike

我设法使用 jQuery.ajax() 获取 JSON 内容。目前,它从包含单个 index.php 文件的另一台主机获取内容,该文件返回带有以下正文的 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 正文和 xhr.status code> 返回 401)。但对于 Authorization header ,主体不会返回任何内容,并且 xhr.status 返回 0

我需要在该 header 中发送身份验证 token 。

最佳答案

我使用 Node.js 做了同样的事情,并注意到它发送了两个请求/响应。一个带有 204 header ,另一个带有预期的 401 和 json 正文。第一种方法是 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]);
}

工作正常。

关于javascript - 无法获取 401 响应正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31749662/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com