Chrome is caching an HTTP PUT request

2019-03-13 07:07发布

问题:

I have this bizarre issue with Chrome. It quite often appears to cache PUT requests.

The Details: I have an app using backbone.js and when trying to persist some changes to a model (backbone automatically generates a PUT request), Chrome just wont send that request to the server. It works perfectly fine in Firefox and IE (haven't seen the issue in Safari so far).

Here's a screenshot from the Chrome developer tools' Network tab. As you can see, the response for the PUT request is being returned from cache (the request doesn't hit the server!!)

Here's a screenshot of the header details of that same request. Once again, it's evident that Chrome doesn't bother sending the PUT request to the server.

The payload of the request is JSON data. Any thoughts as to why this is happening / what I'm doing wrong?

UPDATE: Chromium has confirmed that this is indeed a bug on it's end (thanks Jan Hančič).

TEMPORARY SOLUTION I ended up overriding Backbone.sync method and appending a timestamp to the querystring of PUT, POST and DELETE requests so that they are always unique:

if(!options.data && model && (method == 'create' || method == 'update' || method == 'delete')) {
    params.url += (params.url.indexOf('?') == -1 ? '?' : '&') + '_=' + new Date().getTime();
}

回答1:

I use extra parameter to avoid caching:

url += '?_dc=' + Math.random().toFixed(20).replace('.', '');

I don't interpret this parameter on server side.

EDIT: Besides of chrome there are a lot things could cache requests - user's proxy server for instance. I think additional query parameter is a good solution to keep out of caching.



回答2:

Backbone use jQuery or Zepto to make the AJAX request. Assuming that you are using jQuery, set the cache off.

Run this to set the cache off in the overall application so you will not need to worry about cache:

$.ajaxSetup({
      cache : false
});

If keep the cache on is important for your business, I think that you could do something like this for specific no cache calls:

model.save({}, {cache:false});