简体   繁体   English

Rails控制器接受json POST请求

[英]Rails controller accept json POST request

How can I set up my rails project to accept a json HTTP POST request? 如何设置我的rails项目以接受json HTTP POST请求? I'm a beginner to rails and have tried different things but cant capture any data. 我是rails的初学者并尝试了不同的东西,但无法捕获任何数据。 So far this is my controller method. 到目前为止,这是我的控制器方法。

def flowplayer_callback
    pars = params[:video]
end

I have this in my routes.rb file: 我在routes.rb文件中有这个:

post "flowplayer_callback" => "videos#flowplayer_callback", :via => [ :post]

Incoming json will look similar to this: 传入的json看起来与此类似:

{"video": { "id": 85067, "seconds": 48, "failed": 0, "encodings": [{ "id": 263445, "duration": 23 }, { "id": 263446, "duration": 23 }] }

Edit: My issue was with devise gem trying to authenticate user in the before action. 编辑:我的问题是设计宝石尝试在之前的操作中验证用户。

If the Content-Type header of your request is set to application/json , Rails will automatically load your parameters into the params hash. 如果请求的Content-Type标头设置为application/json ,则Rails会自动将参数加载到params哈希中。 Read a bit more about this here: 在这里阅读更多相关信息:

http://edgeguides.rubyonrails.org/action_controller_overview.html#json-parameters http://edgeguides.rubyonrails.org/action_controller_overview.html#json-parameters

Additionally, unless you've disabled it, you'll have Strong Parameters blocking anything you haven't permitted. 此外,除非您已禁用它,否则您将使用强参数来阻止您不允许的任何内容。

You should permit the things you're willing to accept in your controller action (or set up a private method if you need to permit them in more than one place, such as create and update methods): 您应该在控制器操作中允许您愿意接受的内容(或者如果您需要在多个位置允许它们,则设置私有方法,例如创建和更新方法):

def flowplayer_callback
  pars = params.require(:video).permit(:id, :seconds, encodings: [:id, :duration])
end

I'm not sure what's going on with your :failed section of data as your hash is somewhat broken. 我不确定你的:failed数据:failed部分是怎么回事,因为你的哈希值有点坏了。 But, you should get the idea for what you need to do. 但是,你应该了解你需要做什么。

Read more about Strong Parameters here - http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters 在此处阅读有关强参数的更多信息 - http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters

It could be that you need to set the correct headers before making your post request, in order for rails controller to accept a json response. 可能是您需要在发出请求之前设置正确的标头,以便rails控制器接受json响应。

Content-Type: application/json
Accept: application/json

This SO response has some more details https://stackoverflow.com/a/4914925 这个SO响应有更多细节https://stackoverflow.com/a/4914925

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM