为了账号安全,请及时绑定邮箱和手机立即绑定

nikic/FastRoute post请求参数访问

nikic/FastRoute post请求参数访问

PHP
精慕HU 2023-09-22 14:55:52
我正在尝试使用 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,但是,它是空的。
查看完整描述

1 回答

?
摇曳的蔷薇

TA贡献1793条经验 获得超6个赞

在搜索了大量有关 nikic/FastRoute post 请求的信息后,对代码进行了以下更改。

$_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";

  }

}



查看完整回答
反对 回复 2023-09-22
  • 1 回答
  • 0 关注
  • 92 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信