428 Precondition Required는 서버가 이 요청을 반드시 조건부(conditional)로 보내도록 요구한다는 뜻입니다. 클라이언트가 If-Match 같은 전제 조건 헤더 없이 쓰기 요청을 보내면, 서버가 이를 거부하고 조건을 붙이라고 요구합니다.
이 코드의 목적은 '잃어버린 갱신(lost update)' 방지입니다. 두 클라이언트가 같은 리소스를 각자 조회한 뒤 순서대로 저장하면 뒤 저장이 앞 저장을 조용히 덮어씁니다. 서버가 If-Match를 강제하면 이런 무조건적 덮어쓰기를 막을 수 있습니다.
PUT /docs/42 HTTP/1.1
Host: api.example.com
Content-Type: application/json
{"title":"New"}HTTP/1.1 428 Precondition Required
Content-Type: application/json
{"error":"precondition_required","hint":"Include an If-Match header with the current ETag."}app.put('/docs/:id', (req, res) => {
if (!req.headers['if-match']) {
return res.status(428).json({
error: 'precondition_required',
hint: 'Include an If-Match header with the current ETag.'
});
}
// proceed with the conditional update...
});