0
votes

I have an API to handle cache control. Server will set response header "last-modified" and next request from browser will have If-modified-Since header.

However, when I use ajax to request API, it will not set If-modified-Since header automatically. And I set If-modified-Since in ajax request header, server response 304 status code. But response body is empty.

Is ajax need to manually to fulfill browser behavior about cache control?

Is there better solution?

I find a similar question here.

2

2 Answers

0
votes

The response body should be empty for a 304 response, that's how it's intended to work. The protocol states:

The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.

So, if you send the request with the If-modified-since and the condition is not met, you won't get a response body (the actual data). You're basically stating that you have the content and you want it only if it updated.

Try to not use the If-Modified-Since header and instead use the Cache-control header:

$.ajax({
...
headers: {
     'Cache-Control': 'max-age=1000' 
}
...
});
0
votes

Finally, it resolved after I study this.

Setting Request Header to

'Cache-Control': 'max-age=0'

If response provide Last-Modified header, next request will automatically set If-Modified-Since and value is equal.

When 304 response occur, response content is from browser cache.