【问题标题】:What is the difference between two routes in Mojolicious?Mojolicious 的两条路线有什么区别?
【发布时间】:2017-01-05 13:45:10
【问题描述】:

我只是创建了两条路线:

$r->any  ( '/api/v:api', [ api => qr/\d+/ ], { api => 1 } )->partial( 1 );
$r->under( '/api/v:api', [ api => qr/\d+/ ], { api => 1 } );

似乎两者的工作方式相同。

它们之间有什么区别?

UPD
我注意到对于第一种情况(->any),静态文件的链接被移动到/api/v1。这在发生异常时很明显。 mojo/debug 模板尝试从/api/v1/... 路径而不是/... 加载静态文件。 为什么?

【问题讨论】:

    标签: perl mojolicious


    【解决方案1】:

    under 在调用之前调用。您可以在其中放置验证码。

    use strict;
    use warnings;
    use Mojolicious::Lite;
    
    under sub {
        my $self = shift;
        my $api_key = $self->req->url->to_abs->username;
        my $api_secret = $self->req->url->to_abs->password;
    
        if($api_key ne "Admin" && $api_secret ne "Password123") {
            $self->res->headers->www_authenticate('Basic');
            $self->render(text => 'Error: API-Credentials are wrong', status => 401);
            # No routes will be executed
            return undef;
        }
    
        # Authentication with success, execute other routes
        return 1;
    }
    
    # Only executed if the url is http://Admin:Password123@127.0.0.1:3000
    any '/' => sub  { 
        my $self = shift; 
        my $date = Mojo::Date->new; 
        $self->render(text => $date, status => 200);
    }; 
    

    您必须将其置于要保护的例程之上,这一点非常重要。

    【讨论】:

    • anypartial 匹配怎么样?利弊
    • 'any' 可以采用 HTTP 方法进行匹配,但不能。 $r->any(['GET', 'POST'])。当我使用 DELETE 发送 HTTP 请求时,您的 API 在做什么?使用 POST 访问时是否返回相同的资源?这是一个糟糕的 API 设计。
    猜你喜欢
    • 2017-04-06
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    相关资源
    最近更新 更多