【问题标题】:Passing data via URL with a post request in Slim在 Slim 中通过带有 post 请求的 URL 传递数据
【发布时间】:2020-06-02 22:50:31
【问题描述】:

我正在创建一个 API,我想知道是否有任何方法可以通过带有 post 方法的 URL 传递数据

add?name={name}&age={age}…

我没有太多 API 开发经验,但我记得这个 URL 在 Spring Boot 中可以使用。

提前致谢。

【问题讨论】:

    标签: php rest spring-boot api slim


    【解决方案1】:

    首先,创建一个不带任何查询参数来处理 POST HTTP 请求的路由。

    $app->post('/add', function (Request $request, Response $response, array $args) {
        // get query parameters as an associative array
        $params = $request->getQueryParams();
    
        // return $params as a JSON data
        $response->getBody()->write(json_encode($params));
        return $response->withHeader('Content-Type', 'application/json');
    });
    

    然后,使用您的查询参数向该路由发出 POST HTTP 请求:/add?name=Foo&age=27

    输出:

    {
        "name": "Foo",
        "age": "27"
    }
    

    【讨论】:

      【解决方案2】:

      您可以像在任何类型的 HTTP 请求中一样在 URL 中传递数据。 也就是说,在使用 POST / PUT / PATCH 时,我建议使用作为请求正文发送的 JSON 有效负载。

      如果你想在 Slim 中读取参数

      <?php
      $app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
      
          $name = $args['name'];
      
          // or
          $name = $request->getArgument('name');
      
          // When Request URL is
          // /hello/world?age=24
          // you can read the age argument as
          $name = $request->getArgument('age');
      
          // This behaviour is defined in PSR-7 and available across PHP frameworks
      
          return $response;
      });
      

      在普通 PHP 中,您可以使用超全局 $_GET 或 $_POST 读取参数

      <?php
      $name = $_GET['age'];
      

      【讨论】:

        猜你喜欢
        • 2018-12-31
        • 1970-01-01
        • 1970-01-01
        • 2018-12-09
        • 2021-01-02
        • 1970-01-01
        • 1970-01-01
        • 2021-11-01
        • 2021-12-22
        相关资源
        最近更新 更多