Ruby-on-rails 在 Rails 4 中接收 POST 数据并读取 request.body
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19919780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Receiving POST data in Rails 4 and reading request.body
提问by Davey
I want to send a POST request to a rails application and have it save and parse the request body in the database...
我想向 Rails 应用程序发送 POST 请求,并让它保存并解析数据库中的请求正文...
My route on the receiving end is currently setup as:
我在接收端的路由目前设置为:
post '/request' => 'controller#receives_data'
when I post data to this controller I use:
当我将数据发布到这个控制器时,我使用:
def post_it
connection.post(uri.path, "this is data", header_with_authkey)
end
My controller method that receives the post is setup as:
我接收帖子的控制器方法设置为:
def receives_data
log(request.body.read)
end
However I am getting a 422 error, unprocessable entity, and the log file is always empty...
但是我得到了一个422 error, unprocessable entity,并且日志文件总是空的......
Are there specific headers I need to include to post this to a rails app? Are there specific configurations I need to include in my controller or routes?
是否需要包含特定的标题才能将其发布到 rails 应用程序?我的控制器或路由中是否需要包含特定配置?
采纳答案by aartikriplani
You'll need to set the following headers in your post.
您需要在帖子中设置以下标题。
Content-Type: application/json
Accept: application/json
回答by feipinghuang
request.raw_post
Read the request body. This is useful for web services that need to work with raw requests directly.
读取请求正文。这对于需要直接处理原始请求的 Web 服务很有用。
http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-raw_post
http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-raw_post

