我是Perl和Mojo的新手,在从Angular接收POST数据时遇到了一个问题:
我的AngularCode是
var datainput = JSON.stringify({"test":"orcl"});
$http.post('http://localhost/perltest/perltest.pl/post', datainput)
.success(function(data, status, headers, config) {
console.log("post geschickt");
console.log(headers());
console.log(data);
console.log("data back: " + JSON.stringify(data));
alert(JSON.stringify(data));
})我的Mojo-Sub看起来像:
post '/post' => sub {
my $self = shift;
my $json = $self->req->json;
print header(-type => "text/html");
print Dumper($json->{test});
};
app->start;我得到的结果是:$VAR1 = undef;Content-Length: 0状态: 404未找到日期:星期五,2017年1月20日09:49:57 GMT
怎么啦?在我看来,$json = $self->req->json没有从POST中获得JSON-String?
发布于 2017-02-27 07:14:36
Angular通过请求的主体传递帖子,所以这就是我处理那些帖子的方式。
post '/post' => sub {
my $self = shift;
my $json = $self->req->body;
#use Mojo::JSON qw(decode_json encode_json) at top of app
my $perl_hash = decode_json($json)
#Do something with the hash, like pass to a helper or model
$self->render(json => $return_from_model_or_helper);
};Jquery post将使用params而不是body。
发布于 2017-01-20 19:21:59
docs for the json method表示,如果解码不起作用或请求为空,则返回undef。您应该首先查看请求正文。
warn Dumper $self->req->body;这会将原始请求正文输出到您的应用程序控制台或日志。如果您运行morbo app.pl,则这是您的控制台窗口。看看你看到了什么。内容在那里吗?内容类型是否正确?
那就从那里开始吧。
您不能只在路由处理程序中间使用print。您需要使用render对象来应用您的内容。
post '/post' => sub {
my $self = shift;
my $json = $self->req->json;
$self->render( text => $json->{test} );
};这样,Mojolicious会为你处理所有的事情。也不需要显式设置内容类型。它会自动使用一些合理的东西。
但是,你会拿回404分。这可能是因为print,但我不确定。
发布于 2017-01-21 01:44:21
404 Not Found表示找不到该资源。请仔细检查您的应用程序是否在http://localhost/perltest/perltest.pl/post.Data::Dumper.https://stackoverflow.com/questions/41760648
复制相似问题