如何使用fetch从API获取指定数据并将目标字段存入变量?
使用Fetch请求API并提取name字段值
你可以通过以下两种常用方式,用fetch请求目标API并将返回的name字段值存入变量:
方式一:async/await写法(推荐,代码可读性更高)
async function getUserName() { try { // 发送API请求 const response = await fetch('你的API地址'); // 校验请求是否成功 if (!response.ok) { throw new Error(`请求失败:${response.status}`); } // 将响应转为JSON格式 const data = await response.json(); // 提取name字段存入变量 const userName = data.name; // 这里可以添加userName的后续使用逻辑 console.log(userName); return userName; } catch (error) { // 处理请求过程中的各类错误 console.error('请求出错:', error); } } // 调用函数触发请求 getUserName();
方式二:Promise链式调用写法
fetch('你的API地址') .then(response => { // 校验响应状态 if (!response.ok) { throw new Error(`请求失败:${response.status}`); } return response.json(); }) .then(data => { // 提取name字段 const userName = data.name; console.log(userName); // 后续业务逻辑写在此处 }) .catch(error => { // 捕获并处理错误 console.error('请求出错:', error); });
关键注意事项
- 替换代码中的
你的API地址为实际的API接口URL - 必须校验
response.ok,避免在请求失败时继续解析数据 - 一定要添加错误捕获逻辑,覆盖网络故障、JSON解析失败等异常场景
内容的提问来源于stack exchange,提问作者Mustafa
相关产品推荐
相关产品推荐

