Receiving POST data in Rails 4 and reading request.body
47,146
Solution 1
You'll need to set the following headers in your post.
Content-Type: application/json
Accept: application/json
Solution 2
request.raw_post
Read the request body. This is useful for web services that need to work with raw requests directly.
http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-raw_post
Related videos on Youtube
Author by
Davey
Updated on July 09, 2022Comments
-
Davey almost 2 years
I want to send a POST request to a rails application and have it save and parse the request body in the database...
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...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?
-
mechanicalfish over 10 yearsWhat content type are you using in your request?
-
Davey over 10 yearsThe only header I specify is my authorization token.
-
-
Davey over 10 yearsDoes the Net::HTTP post method always send the data as JSON data?
-
aartikriplani over 10 yearsYou should set Content-Type: header field for POST. If no Content-Type: field given, this method uses “application/x-www-form-urlencoded” by default. Read here -> ruby-doc.org/stdlib-2.0.0/libdoc/net/http/rdoc/Net/…
-
aartikriplani over 10 yearsIf that doesn't work, it could alternatively be due to this bug -> github.com/rails/rails/issues/11402. Check the version you are using.