【问题标题】:Can't send HTTP response as xml using mojolicious无法使用 mojolicious 将 HTTP 响应作为 xml 发送
【发布时间】:2014-04-09 04:17:20
【问题描述】:

在这里尝试学习 Mojolicious。对于以下请求,当我尝试访问时得到 404

http://hostname:3000/xml

这是简单的脚本:

use Mojolicious::Lite;
use Data::Dumper;


get '/xml' => sub {
    my $self  = shift;
    $self->render(xml => "<employees>  
 <employee>  
      <id>1001</id>  
       <name>John Smith</name>  
 </employee>  
 <employee>  
      <id>1002</id>  
       <name>Jane Dole</name>  
 </employee>  
 </employees>"
    );
};

app->start;

此脚本是从 json 的示例中采用的,它运行良好。不知道为什么 xml 不起作用。

【问题讨论】:

    标签: perl mojolicious


    【解决方案1】:

    只需要指定一个format

    get '/xml' => sub {
        my $self  = shift;
    
        my $xml = <<'XML';
    <employees>
    <employee><id>1001</id><name>John Smith</name></employee>
    <employee><id>1002</id><name>Jane Dole</name></employee>
    </employees>
    XML
    
        $self->render(data => $xml, format => 'xml');
    };
    

    响应标头等于以下内容:

    Connection: keep-alive
    Server: Mojolicious (Perl)
    Content-Length: 140
    Content-Type: application/xml
    Date: Wed, 09 Apr 2014 05:36:05 GMT
    
    200 OK
    

    当然也可以将数据放在模板中:

    get '/xml' => sub {
        my $self  = shift;
    
        $self->render('employees', format => 'xml');
    };
    
    app->start;
    
    __DATA__
    
    @@ employees.xml.ep
    <employees>
    <employee><id>1001</id><name>John Smith</name></employee>
    <employee><id>1002</id><name>Jane Dole</name></employee>
    </employees>
    

    【讨论】:

    • 感谢@Miller 的快速回答!效果很好。
    猜你喜欢
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多