JavaScript HTTP 请求:使用 fetch 函数发送 API 请求
使用 JavaScript 发出 HTTP 请求,可以使用内置的 'XMLHttpRequest' 对象或 'fetch' 函数。我将提供使用 'fetch' 函数的示例代码:
async function sendHttpRequest(url, method, headers, body) {
try {
const response = await fetch(url, {
method: method,
headers: headers,
body: body
});
const data = await response.json();
return data;
} catch (error) {
// 处理错误
console.error('发生错误:', error);
return null;
}
}
// 调用示例
const url = 'https://api.example.com/endpoint';
const method = 'POST'; // 可以是 'GET'、'POST'、'PUT'、'DELETE' 等
const headers = {
'Content-Type': 'application/json' // 根据需要设置其他头部
};
const body = JSON.stringify({ key: 'value' }); // 根据需要发送的数据
sendHttpRequest(url, method, headers, body)
.then(responseData => {
// 处理返回的数据
console.log('收到的数据:', responseData);
});
上述代码使用 'fetch' 函数发送 HTTP 请求。你可以将请求的 URL、请求方法、头部信息和请求体作为参数传递给 'sendHttpRequest' 函数。它将返回一个 Promise,可以使用 '.then()' 处理返回的数据。
原文地址: https://www.cveoy.top/t/topic/b3Gs 著作权归作者所有。请勿转载和采集!