实现说明
各个操作都建立在顶层绑定之上:headers、response。
使用要点
- 演示输出是带标签的(
append joins:、set replaces:、entries:),每个操作都会留下自己的一行标注。
常见问题
这段代码会引入外部包吗?
不涉及外部包,每个调用都落在内建 API 上。 文件的状态由几个模块级绑定持有:headers、response。
核心语句
const headers = new Headers({ accept: 'application/json' });
response.headers.append('set-cookie', 'session=abc');
response.headers.append('set-cookie', 'theme=dark');
代码示例
// Headers.append joins repeated values; set replaces them wholesale.
const headers = new Headers({ accept: 'application/json' });
headers.append('x-trace-id', 'trace-a');
headers.append('x-trace-id', 'trace-b');
console.log('append joins:', JSON.stringify(headers.get('x-trace-id')));
headers.set('x-trace-id', 'trace-c');
console.log('set replaces:', JSON.stringify(headers.get('x-trace-id')));
// Iteration yields one combined entry per header name
console.log('entries:', JSON.stringify([...headers.entries()]));
// Set-Cookie must never be joined, so getSetCookie exposes the real list
const response = new Response();
response.headers.append('set-cookie', 'session=abc');
response.headers.append('set-cookie', 'theme=dark');
console.log('set-cookie get:', JSON.stringify(response.headers.get('set-cookie')));
console.log('set-cookie list:', JSON.stringify(response.headers.getSetCookie()));
// has() reports presence without reading the value
console.log('has accept:', headers.has('accept'), '| has x-missing:', headers.has('x-missing'));