Rest API 사용시 Caching 주의
본문 바로가기

Network&etc/HTTP

Rest API 사용시 Caching 주의

이미지파일이나 css, js에서만 캐시가 가능한줄 알았는데(Cacheable) Rest API에서도 가능하다는것을 배우게되었다.

Get 요청, Head의 경우 웹브라우저상에서 캐싱이 쌓이기 때문에

데이터는 변경될지언정 웹브라우저에서 상에서는 이전 데이터를 보여줄수있으니 매우 주의 ㅠㅠㅠ...

여담으로 다른 메소드(post, patch)들은 본문내용까지 캐시키로 고려해야해서 구현이 쉽지안다고함

 

캐시로 쓰이는지 확인하는법

네트워크 탭에서 status가 연한색이면 캐시가 활용된것이라함

캐시에서 활용되었다?

해결 방법1 쿼리스트링추가

1~1000까지의 랜덤한 숫자를 쿼리스트링으로 붙여서 캐싱문제를 해결함

let randomNum = Math.floor(Math.random() * 1000 + 1)
await fetch(`...?v=${randomNum}`,option)

 

해결 방법2 request header에 옵션추가

const option = {
    headers:{
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache'//하위 HTTP 1.0호환
    }
}
await fetch(`...`,option)

cache-contorl에는 종류가 무척많은것같다.

no-cache뿐만아니라 max-age는 예를들어 60일경우 60초동안 캐시가 유효하다고함

단 max-age를 쓸경우 60초이후에 캐시가만료되어 서버에 다시요청하더라도 서버에서 데이터를 변경하지않을수도있음 그럴경우를 대비하여 데이터최종수정일 last-modified라는 옵션등도 추가해줘야함!

 

좀더 공부해봐야겠다.

 

https://restfulapi.net/caching/

 

Caching REST API Response

Caching, in REST, is the ability to store copies of frequently accessed data in several places along the request-response path.

restfulapi.net

https://stackoverflow.com/questions/866822/why-both-no-cache-and-no-store-should-be-used-in-http-response

 

Why both no-cache and no-store should be used in HTTP response?

I'm told to prevent user-info leaking, only "no-cache" in response is not enough. "no-store" is also necessary. Cache-Control: no-cache, no-store After reading this spec http://www.w3.org/Protocols/

stackoverflow.com

 

반응형