![](/img/trans.png)
[英]PHP - nikic/FastRoute routes for Middlewares\FastRoute package
[英]nikic/FastRoute post request parameter access
我正在嘗試使用 FastRoute 實現簡單的 POST 請求。 我按照給定的示例成功實現了 GET 類型的請求。 在實現 POST 請求時,我無法訪問隨請求發送的參數。
$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
$r->addRoute('POST', '/login', 'Test/put');
$r->addRoute('GET', '/users/{id:\d+}', 'Test/put');
});
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
if (false !== $pos = strpos($uri, '?')) {
$uri = substr($uri, 0, $pos);
}
$uri = rawurldecode($uri);
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
switch ($routeInfo[0]) {
case FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
list($class, $method) = explode("/", $handler, 2);
call_user_func_array(array(new $class, $method), $vars);
break;
}
class Test {
public function put() {
return "Check";
}
}
我試圖檢查$_POST ,但是,那是空的。
在搜索了有關 nikic/FastRoute 發布請求的大量信息后,偶然發現了這個stackoverflow 帖子。 之后對代碼進行了以下更改。
$_POST = json_decode(file_get_contents('php://input' ),true);
$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
$r->addRoute('POST', '/login', 'Test/put');
$r->addRoute('GET', '/users/{id:\d+}', 'Test/put');
});
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
if (false !== $pos = strpos($uri, '?')) {
$uri = substr($uri, 0, $pos);
}
$uri = rawurldecode($uri);
$httpMethod = $_SERVER['REQUEST_METHOD'];
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
switch ($routeInfo[0]) {
case FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = ($httpMethod == 'POST')? $_POST : $routeInfo[2];;
list($class, $method) = explode("/", $handler, 2);
call_user_func_array(array(new $class, $method), $vars);
break;
}
class Test {
public function put() {
return "Check";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.