dousong3760 2016-11-17 11:28
浏览 23
已采纳

Slim Framework v3 - 与AND没有最终'/'的相同路由

I created a small application with SlimFramework v3 and I am able to build a simple route like this:

// GET localhost/admin
$app->get('/admin', function(){
    # code here
});

My problem is that this work only for localhost/admin and not for localhost/admin/ (with final backslash). Is there any option to use ONE route for both?

  • 写回答

1条回答 默认 最新

  • dongzhenqi2015 2016-11-17 11:41
    关注

    There are 2 possibilities

    1. Specify an optional /

      $app->get('/admin[/]', function(){
          # code here
      });
      
    2. Add middleware that redirects routes with an ending / to the url without that.

      use Psr\Http\Message\RequestInterface as Request;
      use Psr\Http\Message\ResponseInterface as Response;
      
      $app->add(function (Request $request, Response $response, callable $next) {
          $uri = $request->getUri();
          $path = $uri->getPath();
          if ($path != '/' && substr($path, -1) == '/') {
              // permanently redirect paths with a trailing slash
              // to their non-trailing counterpart
              $uri = $uri->withPath(substr($path, 0, -1));
      
              if($request->getMethod() == 'GET') {
                  return $response->withRedirect((string)$uri, 301);
              }
              else {
                  return $next($request->withUri($uri), $response);
              }
          }
      
          return $next($request, $response);
      });
      

      (Source: http://www.slimframework.com/docs/cookbook/route-patterns.html)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?