fetch() 发起 get 请求分三步:调用函数、处理响应、解析 json;默认为 get,需用 response.json() 解析数据,推荐 async/await 写法并用 try/catch 统一捕获错误。

直接用 fetch() 发起 GET 请求很简单,核心是调用函数、处理响应、解析 JSON,三步到位。
基础语法:发起请求并读取 JSON 数据
fetch() 默认就是 GET 请求,不需要额外配置方法。关键是要用 .then() 链式处理响应体,并显式调用 response.json() 才能得到真正的数据对象:
- 调用
fetch(url)返回一个 Promise,代表网络响应(不是数据本身) - 响应对象有
.json()方法,它也返回 Promise,用于解析响应体为 JavaScript 对象 - 记得用
.catch()捕获网络错误或解析失败(比如服务器返回非 JSON 内容)
示例:
Java Maven 项目审查工作流的通用输入处理。当 Java Maven 项目以 ZIP压缩包或 GitLab 仓库 URL 形式提供且需要...时使用。
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data.title)) // 输出 "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
.catch(err => console.error('请求失败:', err));
带查询参数的 GET 请求
URL 中的查询参数不能直接拼字符串(易出编码问题),推荐用 URLSearchParams 构造:
- 创建参数对象,传入
URLSearchParams - 将结果附加到 URL 后面,自动处理编码和
?/&拼接
示例:
const params = new URLSearchParams({ userId: 1, _limit: 5 });fetch(`https://jsonplaceholder.typicode.com/posts?${params}`)
.then(r => r.json())
.then(posts => console.log(posts.length)); // 输出 5
设置请求头(如认证或内容类型)
虽然 GET 请求通常不需要请求体,但有时需添加 headers(比如 Bearer Token):
- 通过
fetch(url, options)的第二个参数传入配置对象 -
headers是一个普通对象,键名大小写不敏感,值必须是字符串 - 常见场景:添加
Authorization或Accept头
示例:
fetch('https://api.example.com/data', {headers: {
'Authorization': 'Bearer abc123',
'Accept': 'application/json'
}
})
.then(r => r.json())
.catch(e => console.error(e));
使用 async/await 写法更清晰
相比链式 .then(),async/await 让异步逻辑更接近同步阅读习惯,错误处理也更直观:
- 函数需声明为
async - 用
await fetch(...)等待响应,再await response.json() - 用
try/catch统一捕获网络错误、状态异常、JSON 解析错误
示例:
async function getPost(id) {try {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
return data;
} catch (err) {
console.error('获取失败:', err);
}
}
getPost(1).then(post => console.log(post.title));
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










