首页 > 解决方案 > 为什么 POST 被解释为 GET?

问题描述

我正在尝试使用提交表单设置基本路由。

HTML:

<form method="POST" action="/names">
   <input name="name"></input>
   <button type="submit">Submit</button>
</form>

PHP:

class Router {
    public $routes = [
        'GET' => [],
        'POST' => []
    ];

    public function get($uri, $controller){
        $this->routes['GET'][$uri] = $controller;
    }

    public function post($uri, $controller){
        $this->routes['POST'][$uri] = $controller;
    }

    public function direct($uri, $requestType){
        if(array_key_exists($uri, $this->routes[$requestType])){
            return $this->routes[$requestType][$uri];
        }

        throw new Exception('No route defined for this uri');   
    }
}

$router = new Router;

$router->get('', 'index.view.php');
$router->post('names', 'add-name.php');

class Request {
    public static function uri(){
        return trim(
            parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH),'/'
        );
    }

    public static function method(){
        return $_SERVER['REQUEST_METHOD'];
    }
}

require $router->direct(Request::uri(), Request::method());

但每次我提交时,它只会说“没有为此 uri 定义路由”而且我认为问题在于 POST 请求被解释为 GET。当我尝试

var_dump(Request::uri());
var_dump(Request::method());

它说 string(5) "names" string(3) "GET"

我真的很困惑为什么会这样。任何想法为什么 POST 切换到 GET?

标签: php

解决方案


推荐阅读