Can't get 401 response body

霸气de小男生 提交于 2019-12-11 10:04:55

问题


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}.

This is the 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');
}

And the 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;

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.


回答1:


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]);
}

Works fine.



来源:https://stackoverflow.com/questions/31749662/cant-get-401-response-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!