Headers go first
Watch what happens when you set a header after writing part of the body.
const http = require('node:http');const server = http.createServer((req, res) => { res.setHeader('x-step', 'one'); res.write('part 1, '); console.log('headersSent: ' + res.headersSent); try { res.setHeader('x-late', 'two'); } catch (err) { console.log(err.code); } res.end('part 2');});server.listen(0, async () => { const { port } = server.address(); const r = await fetch(`http://localhost:${port}`); console.log('x-step: ' + r.headers.get('x-step')); console.log('x-late: ' + r.headers.get('x-late')); console.log(await r.text()); server.close();});1. Predict the output
Tap the lines in the order you think they print.
- 1…
- 2…
- 3…
- 4…
- 5…