How “304 Not Modified” works?

血红的双手。 提交于 2019-11-26 07:57:20

问题


  • How \"304 Not Modified\" is generated?

  • How does a browser determine whether the response to a http request is 304?

  • Is it set by the browser or sent from the server?

  • If sent by server, how does server know the data available in cache, also how does it set 304 to an image?

My guess, if generated by browser

function is_modified()
{
    return get_data_from_cache() === get_data_from_url();
};

function get_data_from_cache()
{
    return some_hash_or_xxx_function(cache_data);
}

function get_data_from_url()
{
     return some_hash_or_xxx_function(new_data);
}

function some_hash_or_xxx_function(data)
{
  // do something with data
  // what is that algorithm.?
      return result;
}

console.log(is_modified());

I am relying on 3rd party API provider to get data, parse & push it to DB. The data may or may not change during every request, but the header always sends 200, I do not want to parse, check the last Unique ID in DB & so on.. to determine the change in data, nor compare the result directly rather I md5(), sha1() & crc32() HASHed the result & works fine, but wondering the algorithm to determine 304.

I want to use same kind of algorithm to determine the change in data.


回答1:


When the browser puts something in its cache, it also stores the Last-Modified or ETag header from the server.

The browser then sends a request with the If-Modified-Since or If-None-Match header, telling the server to send a 304 if the content still has that date or ETag.

The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.




回答2:


Last-Modified : The last modified date for the requested object

If-Modified-Since : Allows a 304 Not Modified to be returned if last modified date is unchanged.

ETag : An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL. If the resource representation at that URL ever changes, a new and different ETag is assigned.

If-None-Match : Allows a 304 Not Modified to be returned if ETag is unchanged.

the browser store cache with a date(Last-Modified) or id(ETag), when you need to request the URL again, the browser send request message with the header:

the server will return 304 when the if statement is False, and browser will use cache.



来源:https://stackoverflow.com/questions/20978189/how-304-not-modified-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!