【问题标题】:Can't get 401 response body无法获得 401 响应正文
【发布时间】:2015-10-23 08:08:04
【问题描述】:

我设法使用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;

如果我删除标题 xhr.setRequestHeader('Authorization', 'Bearer 12345');,一切正常(响应有一个 json 正文,xhr.status 返回 401)。但是使用 Authorization 标头时,正文不会返回任何内容,xhr.status 会返回 0

我需要在该标头中发送身份验证令牌。

【问题讨论】:

    标签: javascript php jquery ajax http-headers


    【解决方案1】:

    我使用 Node.js 做了同样的事情,并注意到它发送了两个请求/响应。一个带有 204 标头,另一个带有预期的 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]);
    }
    

    工作正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      相关资源
      最近更新 更多