NodeJS Program to ETag 304 Cache with Explanation
NodeJS
Hard
HTTP & APIs
26 views
1 min read
81 words
This problem helps you practice core NodeJS fundamentals in a practical way. It builds intuition around etag, cache, when. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Return 304 when If-None-Match matches, else return content with ETag.
Input Format
No input.
Output Format
Start server code.
Constraints
Use a fixed ETag for demo.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
const http = require('http');
const body = 'meetcode data';
const etag = 'W/\"m1\"';
const server = http.createServer((req, res) => {
const inm = req.headers['if-none-match'];
if (inm === etag) {
res.writeHead(304, { ETag: etag });
return res.end();
}
res.writeHead(200, { 'Content-Type': 'text/plain', ETag: etag });
res.end(body);
});
server.listen(3008, () => console.log('http://localhost:3008'));
Output Example
No sample I/O is provided for this question.
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Return 304 when If-None-Match matches, else return content with ETag.
Input / Output
Output
Start server code.
Constraints
Use a fixed ETag for demo.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
const http = require('http');
const body = 'meetcode data';
const etag = 'W/\"m1\"';
const server = http.createServer((req, res) => {
const inm = req.headers['if-none-match'];
if (inm === etag) {
res.writeHead(304, { ETag: etag });
return res.end();
}
res.writeHead(200, { 'Content-Type': 'text/plain', ETag: etag });
res.end(body);
});
server.listen(3008, () => console.log('http://localhost:3008'));
Solutions (0)
No solutions submitted yet. Be the first!