Dancer中如何接收json?

Kar*_* E. 2 perl dancer

我对 Perl 框架 Dancer 非常陌生。截至目前,我有一个 get http 侦听器正在工作。我有一个 Angular 框架试图将 json 字符串发布到 Dancer。我如何检索 json 并可能将其分配给标量变量($json)。

get '/games' => sub {
    header 'Access-Control-Allow-Origin' => '*';
    &loadgames();
    return $games;
};

post '/newgame' => sub {
    header 'Access-Control-Allow-Origin' => '*';
    #what should i put here to retrieve the json string
    #I plan to pass the json string to a sub to convert to XML
};
Run Code Online (Sandbox Code Playgroud)

我不确定我是否选择 Dancer 作为获取和发布数据的后端框架。

谢谢您的帮助!

Gra*_*ean 5

如果您的 HTTP 请求具有 JSON 正文 ( Content-type: application/json) 而不是 HTML 表单帖子,那么您可能需要如下所示的内容:

post '/url-path' => {
    my $post = from_json( request->body );
    # do something with the POSTed data structure
    # which would typically be a hashref (or an arrayref)
    # e.g.: schema->resultset('Widget')->create($post);
}
Run Code Online (Sandbox Code Playgroud)

该例程是Dancer 提供的DSL 关键字from_json之一。