Etag header not working, returns status 200 each time

Viewed 769

I want to cache response returned from server using etags. Below is my java based configuration:

    @Bean
    public FilterRegistrationBean<ShallowEtagHeaderFilter> shallowEtagHeaderFilter() {
        FilterRegistrationBean<ShallowEtagHeaderFilter> filterRegistrationBean = new FilterRegistrationBean<>(
                new ShallowEtagHeaderFilter());
        filterRegistrationBean.addUrlPatterns("/endpoint");
        filterRegistrationBean.setName("etagFilter");
        return filterRegistrationBean;
    }

Controller:

    @GetMapping("/endpoint")
    public ResponseEntity<WrappedList> getList(
            @RequestHeader(value = HttpHeaders.IF_NONE_MATCH, required = false) String inm,
            @RequestParam int page) {

            System.out.println(inm);
            return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(0,TimeUnit.SECONDS).cachePrivate().mustRevalidate())
.body(service.getList(page));

    }

I send requests with axios:

Scenario that works (endpoint returns status 304 if resource is not modified):

var etag = '';
document.getElementById("someBtn").addEventListener('click', (event) => {
        event.preventDefault();
    axios({
        method: 'get',
        url: 'http://localhost:8080/endpoint',
        params: {
            page: 1,
        },
        headers: { 
            'If-None-Match': etag
        }
    })
        .then(function (response) {
             etag=response.headers.etag;
        });
});

In this case I store etag in variable and after second request I get status 304. However, storing etags is not something I want to do.

Scenario that doesn't work, but it should(server returns status 200 each time)

document.getElementById("someBtn").addEventListener('click', (event) => {
        event.preventDefault();
    axios({
        method: 'get',
        url: 'http://localhost:8080/endpoint',
        params: {
            page: 1,
        }
    })
        .then(function (response) {
             etag=response.headers.etag;
        });
});

First request: 'If-None-Match' header is not set.

First repsonse: etag header is present.

Second request: 'If-None-Match' header is set with exact same value from first response.

Second response: etag header is present and has the same value as first response etag, however status is 200 and whole response is present. There's also no information that response body was taken from cache.

What am I missing here?

0 Answers
Related