问题描述
我正在开发我的第一个Sinatra应用程序,我很难从发帖请求中获取参数.
I'm working on my first Sinatra app and I have an hard time getting parameters from a post request.
我正在使用MiniTest :: Spec,我的规格看起来像
I'm using MiniTest::Spec and my spec looks like
payload = File.read("./spec/support/fixtures/payload.json")
post "/api/v1/verify_payload", { payload: payload }, { "CONTENT_TYPE" => "application/json" }
last_response.body.must_eql payload
这是我的路线
namespace '/api/v1' do
post '/verify_payload' do
MultiJson.load(params[:payload])
end
end
规范失败,因为last_response.body
为空.
我在这里想念东西吗?
我还尝试从verify_payload
返回整个params
,但在这种情况下,它还返回了一个空字符串.
I also tried to return the entire params
from verify_payload
but also in that case it returned an empty string.
更新
curl -X POST -H "Content-Type: application/json" -d '{"payload":"xyz"}' http://localhost:9292/api/v1/verify_payload
不返回任何内容,并且服务器日志上没有错误
does not return anything and no error on the server log
[2014-01-06 01:16:25] INFO WEBrick::HTTPServer#start: pid=10449 port=9292
127.0.0.1 - - [06/Jan/2014 01:16:27] "POST /api/v1/verify_payload HTTP/1.1" 200 6 0.0220
谢谢
推荐答案
Sinatra只是不解析此数据,因为它们不是表单参数.
Sinatra just don't parse this data, because they are no form parameters.
Form参数如下所示
Form parameter would look like this
您可以仅使用request.body.read
或使用机架贡献来代替参数.
Instead of params you can just use request.body.read
or use rack contrib.
机架控制
- 通过
gem install rack-contrib
安装 -
需要它
- Install it with
gem install rack-contrib
require it
需要机架/容器"
加载use Rack::PostBodyContentTypeParser
与此相关,您可以像往常一样将params
用于json发布数据.像这样:
with this you can use params
as normal for json post data. Something like this:
来源: Sinatra控制器params方法在JSON发布请求中为空,"> http://jaywiggins.com/2010/03/using-rack-middleware-to-parse -json/
这篇关于在Sinatra帖子上读取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!