Don't Forget to Expose Headers When Using Rack CORS
This week I was building an api on Rails and I did implement a cache system based on ETags.
You have a client (mobile application in my case) which needs to fetch data from the server. Most likely you only want to download the payload when something has changed since the last download.
This is the perfect scenario for using ETags.
You set a header (
ETag specifically) with a key that identifies the content being returned. The client gets and saves the key. In the next request, the client sends it through
If the coming key in
If-None-Match is different from the one generated in current response's content, then the server sends new data back to client, otherwise, it returns a
304 Not Modified status meaning that the content is unchanged.
The aforementioned steps can be reproduced using
curl (or any other library):
Response (check the
Now, let's send to the server the gotten
Ok, nothing new so far. What is the matter?
You see that in the
curl's response we are getting the
ETag header as expected.
However, the mobile app I am building is hybrid, so, I need to access cross-origin resources. The Rack CORS gem help us in such task.
After installing the gem, you just need to set the config in any initializer, like below:
The matter is, by default, Rack CORS does not expose any headers except
If your client needs to read another header (like
ETags in this case), you need explicitly expose it:
Having it in mind may save your time.