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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.