JavaScript 集成第三方 API 的核心是使用 fetch 或 XMLHttpRequest 发起请求、处理响应,并安全稳定地使用结果,关键在于认证方式、请求结构、错误处理和跨域限制。
JavaScript 与第三方 API 集成,核心是通过 fetch 或 XMLHttpRequest 发起 HTTP 请求,处理响应数据,并在前端安全、稳定地使用结果。关键在于理解认证方式、请求结构、错误处理和跨域限制。
集成前必须仔细阅读目标 API 的文档,重点关注:
Content-Type: application/json、Authorization)这是最常见场景,比如调用天气或新闻 API:
const API_KEY = 'your_api_key_here';
const url = `https://api.example.com/data?city=beijing`;
fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'appl
ication/json'
}
})
.then(res => {
if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
return res.json();
})
.then(data => console.log(data))
.catch(err => console.error('请求失败:', err));
浏览器会阻止跨域请求(除非 API 明确允许)。常见应对方式:
Access-Control-Allow-Origin: * 或指定域名提升可维护性,统一处理加载状态、错误提示和重试逻辑:
async function callApi(endpoint, options = {}) {
const defaultOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
...options.headers
},
...options
};
try {
const res = await fetch(endpoint, defaultOptions);
if (!res.ok) {
const errorData = await res.json();
throw new Error(errorData.message || `请求失败: ${res.status}`);
}
return await res.json();
} catch (err) {
console.error('API 调用异常:', err);
throw err;
}
}
// 使用示例
callApi('https://api.example.com/users')
.then(users => renderUserList(users))
.catch(showErrorToast);
基本上就这些。不复杂但容易忽略细节——尤其是认证方式和错误边界处理。实际项目中建议配合 TypeScript 类型定义 + 请求拦截器(如用 axios 或自建 hook)进一步提升健壮性。