我正在使用RESTFul API
开发PHP
。例如,以下代码适用于以下代码:
<?php
require('includes/config.php');
$data = array();
try {
$stmt = $db->query('SELECT postID, postTitle, postDesc, postDate,tags FROM blog_posts where inMain=inMain ORDER BY postID DESC LIMIT 5');
$error = false;
$message = "ok";
$i=0;
while($row = $stmt->fetch()){
$tags = explode(",",$row['tags']);
$finalTags = array();
foreach($tags as $item) {
if($item != '' && $item != ' '){
array_push($finalTags,strtolower(trim($item)));
}
}
array_push($data, [
'id' => $row['postID'],
'title' => $row['postTitle'],
'desc' => $row['postDesc'],
'date' => $row['postDate'],
'tags' => $finalTags
]);
}
} catch(PDOException $e) {
$message = $e->getMessage();
$error = true;
}
$response = array();
$response["data"] = $data;
$response["error"] = $error;
$response["message"] = $message;
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
header('Content-Type: application/json');
echo json_encode($response);
?>
从浏览器调用此API可以正常工作。但是当我从JavaScript调用它时,我收到以下错误:
XMLHttpRequest cannot load http://www.example.com/api/v1/getPostsInMain.php. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.
我试图从AngularJs中调用此API,如下所示:
app.factory("Data", ['$http', 'toaster',
function ($http, toaster) { // This service connects to our REST API
var serviceBase = 'http://www.example/v1/';
var conf= { headers: {
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token',
'Content-Type': 'application/json'
}
};
var obj = {};
obj.toast = function (data) {
toaster.pop(data.status, "", data.message, 10000, 'trustedHtml');
}
obj.get = function (q) {
return $http.get(serviceBase + q,conf).then(function (results) {
return results.data;
});
};
obj.post = function (q, object) {
return $http.post(serviceBase + q, object, conf).then(function (results) {
return results.data;
});
};
return obj;
}]);
这是什么问题?您可以在请求和响应中设置所需的标头吗?它与托管我有用吗?
答案 0 :(得分:0)
服务器(PHP)还需要允许CORS。将以下标头添加到PHP脚本的开头:
header("Access-Control-Allow-Origin: *");