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.
Aucun commentaire:
Enregistrer un commentaire