How to return a real empty response in Rails
I’m building a JSON API using rails. In several places I only need to send a 200 http code, without response body.
So, I used the head method:
head :ok
But this returns a response body with one blank character, this single space body causes the mobile client to fail (parse error). Below the response (notice the Content-Length):
HTTP/1.1 200 OK Server: nginx/0.7.67 Date: Tue, 06 Sep 2011 14:13:55 GMT Content-Type: text/html; charset=utf-8 Connection: keep-alive Piictu_version: 1.0.14 Cache-Control: no-cache Content-Length: 1 X-Ua-Compatible: IE=Edge,chrome=1 X-Runtime: 0.273965
So, I created a render_ok method to use instead of head:
def render_ok response.headers['Cache-Control'] = 'no-cache' render json: '' end
And now the response is:
HTTP/1.1 200 OK Server: nginx/0.7.67 Date: Tue, 06 Sep 2011 16:14:05 GMT Content-Type: application/json; charset=utf-8 Transfer-Encoding: chunked Connection: keep-alive Cache-Control: no-cache Etag: "d41d8cd98f00b204e9800998ecf8427e" Piictu_version: 1.0.14 X-Ua-Compatible: IE=Edge,chrome=1 X-Runtime: 0.224352
Now the Content-Length header is not present :). I use render json: '', because I want the Content-Type to be application/json, but you can use render text: '' too.
6 Notes/ Hide
-
foundationex liked this
-
francesuy56 liked this
-
gemfury liked this
-
edgar posted this