【问题标题】:Perl Dancer and defining routes with named parameters and nested prefixesPerl Dancer 和使用命名参数和嵌套前缀定义路由
【发布时间】:2013-12-10 13:01:49
【问题描述】:

最近我一直在与 Dancer 合作创建一个应用程序,但我很难弄清楚如何定义路由。

package MyApp;
use Dancer ':syntax';
our $VERSION = '0.1';

   # Base for routing of requests
   # Match against /:validate

   any '/:validate' => sub {

        # This assumes we can stop the routing here
        # validate the request param in the url string
        # against a regex and 'pass' the request to a
        # specific route with the 'var' option

                var validate => params->{validate};
                .....
                # Validation works and dancer passes successfully
            pass();
   };

   # This is the part that is not working
   prefix '/info' => sub {
       ..... # does stuff
   };    ## back to the root

在通行证的舞者日志中:

[25561] core @0.001133> [hit #1]最后一个匹配的路由通过了!在 /usr/local/share/perl5/Dancer/Route.pm l. 216

在通过后的任何内容的舞者日志中:

[25781] core @0.001524> [命中#4]试图匹配'GET /11121/info/' 反对/^/info$/(从'/info'生成)在 /usr/local/share/perl5/Dancer/Route.pm l. 84 [25781] 核心@0.002041> [点击 #4] 响应:/usr/local/share/perl5/Dancer/Handler.pm l 中的 404。 179

这可能是我缺少的一些简单的东西,但到目前为止我还没有运气。非常感谢任何帮助。

编辑我确实注意到我错误地使用了prefix,所以我修复了这个问题,我为错误的解释道歉。简而言之,例如 url localhost:3000/12/ 的第一部分是一个数据库记录。所有路由都建立在该记录上,该记录是 url 字符串的第一部分,因此我想在进一步进入路由之前对其进行验证。

我能够设置一个 before 钩子来抓取它并可以使用 params 哈希,但它目前在不匹配的模式上出现 500 错误。

        hook before => sub {
            my $route_handler = shift;
            var record => params->{record};

            my $record = var 'record';
            while ($record !~ m/^ID[\-]\d{3,6}$/) {    # Check for valid ID
                    if ($record =~ m/^\d{3,6}$/) {     # Works currently
                            $record = 'ID-'.$record;   
                    }else {forward "/error"};          # this = 500 ISE error
            }
    };

我尝试了forwardsend_error,但都生成了 ISE,Dancer 在日志的最后一个条目中报告了这一点:

29661] 核心@0.001048> [命中#2]在挂钩之前进入 /usr/local/share/perl5/Dancer/Hook.pm l. 58

非常感谢任何帮助,也欢迎编辑以使我的问题更清楚。

【问题讨论】:

  • 您尝试访问的哪个 URL 不起作用?
  • 不清楚你想要实现什么。从上一个日志中可以看出,您的 URL 与您声明的任何路由都不匹配:'GET /11121/info/' against /^/info$/。如果你想使用这个 URL,你需要声明 any '/*/info' 而不是 /info 之类的路由
  • 你的问题到底是什么?

标签: perl dancer


【解决方案1】:

这不是前缀的作用。 Prefix 用于声明当前包中路由的前缀。

prefix '/users';
get '/' => sub { ... };         # matches /users
post '/add' => sub { ... };     # matches /users/add
get '/view/:id' => sub { ... }; # matches /users/view/123

【讨论】:

  • 文档提到前缀的范围可以像prefix '/foo' => sub { ROUTES }。在这种情况下也可以吗?
【解决方案2】:

我根本没有使用过Dancer,但从Dancer::Introduction 文档看来,您还必须在prefix /info 内定义一条路线。尝试:

# This is the part that is not working
   prefix '/info' => sub {
       get '/' => sub {
          ..... # does stuff
       }
   };    ## back to the root

【讨论】:

    猜你喜欢
    • 2011-12-01
    • 2015-11-23
    • 2023-03-08
    • 1970-01-01
    • 2018-03-15
    • 2011-12-23
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    相关资源
    最近更新 更多