使用AngularJS和SlimPHP v3制作CRUD时遇到问题。一切都适用于$ app-> get和$ app->帖子,但是$ app->删除时出错。
我有不同域名的前端和后端,因为我必须设置htaccess将所有内容重定向到index.php才能使Slim正常工作,所以没有成功将正面和背面放在同一个域上。 这是我的index.php
<?php
require __DIR__ . '/vendor/autoload.php';
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
$app = new \Slim\App();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$app->options('/test', function() use($app) {
$response = $app->response();
$app->response()->status(200);
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, X-authentication, X-client');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});
$app->get('/test/', function(Slim\Http\Request $request, Slim\Http\Response $response, array $args) {
$id = $args['id'];
$sql = "SELECT * FROM wp_osoft_orders";
$dbhost = "host";
$dbuser = "user";
$dbpass = "pass";
$dbname = "db";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$headers = $response->getHeaders();
$response = $response->withHeader('Content-type', 'application/json');
$response = $response->withHeader('Access-Control-Allow-Origin', '*');
$headers = $response->getHeaders();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->set_charset("utf8");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$resultsArray = array();
while($row = $result->fetch_assoc()) {
array_push($resultsArray, $row);
}
$response->write(json_encode($resultsArray));
}
else {
$response->write("0 results");
}
$conn->close();
});
$app->delete('/test/{id}', function(Slim\Http\Request $request, Slim\Http\Response $response, array $args) {
$response = $response->withHeader('Access-Control-Allow-Origin', '*');
$response->write("delete is OK");
});
$app->run();
?>
这是我的Angular代码:
function getOrders(){
$http.get("url/test/").success(function(data){
$scope.orders = data;
});
};
getOrders();
$scope.deleteOrder = function (orderId) {
console.log("order to delete id: " + orderId);
$http.delete("url/test/"+orderId).success(function(response){
console.log('delete response: ' + response);
});
getOrders();
};
订单ID我正确地访问了Angular中的console.log,但后来我得到了:
DELETE url / test / 22 XMLHttpRequest无法加载url / test / 22。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许原点'url'访问。响应的HTTP状态代码为400。
每次我写url /我的意思是http://mywebsite.com,但无法用2+链接提问。
感谢您的帮助。
答案 0 :(得分:0)
CorsSlim是您的朋友,它是在Slim Framework世界中启用CORS的更简单方法。使用composer安装并使用它:
$app->delete('/test/{id}', function(Slim\Http\Request $request, Slim\Http\Response $response, array $args) {
$response->write("delete is OK");
})->add(\CorsSlim\CorsSlim::routeMiddleware());
通过这种方式,您可以确保请求中包含必要的标题。
旁注
在您的示例中,您仅在$app->options
而不是/test
上使用/test/{id}
。