我目前正在为一个uni项目开发PHP REST API,该项目使用通过PhoneGap从移动Web应用程序传递的JSON Web令牌,或者在开发过程中使用我的桌面.
使用ajax将令牌发送到我的服务器页面“ friends / read.PHP”时,服务器使用以下命令正确获取了Authorization标头
$headers = getallheaders();
$authHeader = $headers['Authorization'];
但在多次成功运行后停止这样做.此后,将不再提取标头.
我的请求代码如下:
$.ajax({
url: "http://localhost/chordstruck/api/friends/read.PHP",type: "GET",beforeSend: function (request) {
request.setRequestHeader('Authorization','Bearer ' + localStorage.getItem('jwt'));
},datatype: "json",success: function (response) {
console.log(response);
},error: function (jqXHR,textStatus,errorThrown) {
console.log(jqXHR);
}
});
奇怪的是,当使用die(“ test”)过早地杀死PHP脚本,然后再次删除die()时,服务器将开始为多个其他请求选择Authorization标头.
Read.PHP:
<?PHP
error_reporting(E_ALL);
ini_set('display_errors','on');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Origin,Content-Type,Authorization,X-Auth-Token');
$config = require_once '../config/core.PHP';
require_once '../config/jwt_helper.PHP';
// get database connection
include_once '../config/database.PHP';
// instantiate profile object
include_once '../objects/profile.PHP';
$headers = getallheaders();
$authHeader = $headers['Authorization'];
$token;
if ($authHeader) {
list($jwt) = sscanf((string)$authHeader,'Bearer %s');
if ($jwt) {
try {
$key = $config['jwt_key'];
$token = JWT::decode($jwt,$key,array('HS512'));
} catch (Exception $e) {
header('HTTP/1.0 401 Unauthorized');
exit();
}
} else {
header('HTTP/1.0 400 Bad Request');
exit();
}
} else {
header('HTTP/1.0 400 No Header Found');
exit();
}
echo "success";
?>
我在开发此项目时遇到了CORS问题,我在.htaccess文件中与上面的标头以及下面的标头对立了:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
这可能相关吗?任何帮助/想法将不胜感激!
最佳答案
该问题似乎确实与CORS有关,并且在尝试了多种方法之后,以下解决方案现在正在起作用.
原文链接:https://www.f2er.com/jquery/530879.html用以下命令替换read.PHP中的标头:
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
// you want to allow,and if so:
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
// may also be using PUT,PATCH,HEAD etc
header("Access-Control-Allow-Methods: GET,POST,OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
功劳归功于slashingweapon,他用它来回答CORS with php headers