js中有五个结构,共同构成了处理网络请求与响应的核心 API,覆盖从构建请求、管理元数据到解析数据的完整链路。
一、URL
js
const url = new URL('https://api.example.com/users?id=123&name=张三#section1')
url.protocol // "https:" 协议
url.hostname // "api.example.com" 域名
url.port // "" 空字符串 默认端口(https=443/http=80)
url.pathname // "/users" 路径
url.search // "?id=123&name=张三" 参数
url.hash // "#section1" 哈希
const params = url.searchParams; // 操作查询参数
params.append('page', '1'); // 增
params.delete('page'); // 删
params.set('name', '李四'); // 改
params.get('name'); // 查
console.log(params.toString()); // 返回查询字符串 "id=123&name=%E5%BC%A0%E4%B8%89"
二、Headers
js
const headers = new Headers({
'Content-Type': 'application/json' // 初始化时设置请求体格式为 JSON
});
headers.append('Authorization', 'Bearer token'); // 增加认证头
headers.delete('Authorization'); // 删
headers.set('Content-Type', 'text/plain'); // 改 内容类型为纯文本
headers.get('Content-Type'); // 查
headers.has('Content-Type') // 检查是否存在 用于检查是否存在
三、Request
js
const request = new Request("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"key": "value"
})
})
request.url // "https://api.example.com/users"
request.method // "POST"
request.headers // headers对象
request.body // ReadableStream 可读流(不能直接查看内容)
四、Response
js
const response = new Response(JSON.stringify({
success: true,
data: {id: 1, name: "张三"}
}), {
status: 200,
statusText: 'ok',
headers: {
"Content-Type": "application/json"
}
})
// 访问 Response 属性
response.status // 200
response.ok // true(状态码 200-299)
response.statusText // "ok"
response.url // "" (实际响应中会有值"https://api.example.com/users?id=123")
response.headers // headers对象
response.body // ReadableStream,只能读取一次。
response.bodyUsed //表示响应体是否已被读取
// Response 对象只能调用一次 json() 方法
// 然后 response.bodyUsed就会变成true
//其他消费响应体的方法:
response.text()
response.arrayBuffer()
response.blob()
response.formData()
五、json
js
JSON.stringify() // json对象转字符串
JSON.parse() // 字符串转json对象
JSON.stringify() 遇到循环引用会抛出错误(TypeError),不能处理 {a: 1, self: a}
- JSON.stringify() 的undefined 在对象中被忽略,在数组中转为 null
js
// 1. 对象属性 → 被忽略(不是 null!)
JSON.stringify({ a: undefined, b: 1 });
// '{"b":1}' ← a 消失了,不是 "a":null
// 2. 数组元素 → 转为 null
JSON.stringify([undefined, 1]);
// '[null,1]' ← 变成 null 了!
// 3. 单独 undefined
JSON.stringify(undefined);
// undefined ← 不是字符串 "undefined"
| 值 | 在对象中 | 在数组中 | 单独序列化 |
|---|---|---|---|
undefined |
被忽略(属性消失) | 转为 null |
返回 undefined(非有效JSON) |
function |
被忽略 | 转为 null |
返回 undefined |
Symbol |
被忽略 | 转为 null |
返回 undefined |
| Symbol 是 ES6 引入的原始数据类型,表示唯一的标识符。 |
js
// 第三方库和自己代码都用了 'id'
const libId = Symbol('id');
const myId = Symbol('id');
const obj = {
[libId]: '库的ID',
[myId]: '我的ID'
};
// 互不干扰!
console.log(libId === myId); // false 永远唯一
- JSON.parse() 不会忽略任何值,但会严格遵循 JSON 规范:
| 输入 | 结果 | 说明 |
|---|---|---|
'null' |
null |
解析为 null 值 |
'undefined' |
❌ 报错 | undefined 不是有效的 JSON |
'"undefined"' |
"undefined" |
字符串"undefined",合法 |
'{"a": undefined}' |
❌ 报错 | 属性值不能是 undefined |
'{"a": null}' |
{a: null} |
✅ 正常解析 |
'{"a": 1, "b": undefined}' |
❌ 报错 | 整个对象解析失败 |
JSON.stringify() 的第二个参数可以是一个数组,用于指定对象中哪些属性需要被序列化。
js
const user = {
name: 'Alice',
age: 30
};
// 只序列化 name属性
const jsonString = JSON.stringify(user, ['name']);
console.log(jsonString);
// 输出:{"name":"Alice"}
JSON.parse() 的第二个参数 reviver 是一个函数,它在解析过程中对每个键值对调用一次。返回值将作为该键的新值。
js
const user = '{"name": "Alice", "age": "30"}'; // JSON 规范要求键和字符串值必须使用 双引号
const obj = JSON.parse(user, (key, value) => value); // reviver 函数(此处原样返回)
console.log(obj.name); // "Alice"
console.log(obj.age); // "30"