My websites are caching the REST requests. I am happy with the speed of the websites and would like to retain the cache. However, I have discovered that the same file is returned after I have made a POST/PUT/DELETE request. This means that the updated database isn't called. The same happens after refreshing the page. I would like to have updated information from the database after a POST/PUT/DELETE request.
I am just wondering if I can maybe set a conditional statement to cache the files if the last REST request isn't POST/PUT/DELETE? The website is hosted on a shared web hosting platform and I can amend the .htaccess file. Greatly appreciated for any ideas. I hope my explanation is clear but please feel free to reach out if it's not. Thank you in advance
CodePudding user response:
To stop browser caching we can add the below properties in an HTML as meta headers.
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
We have to save the above headers in the html page which will be among the parent HTMLs to be used.
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
The below code can be used from java servlet or nodejs
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setHeader("Expires", "0");
servlet code sample as follows
public void doGet(HttpServletRequest req,HttpServletResponse response) throws ServletException,IOException
{
if(req.get[some field name].equals("last_request")){
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setHeader("Expires", "0");
}
}
Below link can be a reference of this thread