JavaScript 发出 HTTP 请求:使用 Fetch API 的完整指南
使用 JavaScript 发出 HTTP 请求可以使用内置的 XMLHttpRequest 对象或者使用现代的 Fetch API。在 GPT-3.5 Turbo 版中,以下是使用 Fetch API 发出 HTTP 请求的示例代码:
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:', error);
throw error;
}
}
// 调用示例
const url = 'https://api.example.com/endpoint';
const method = 'POST';
const headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_TOKEN'
};
const body = JSON.stringify({ key: 'value' });
sendHttpRequest(url, method, headers, body)
.then(data => {
console.log('Response:', data);
})
.catch(error => {
console.error('Error:', error);
});
在上述示例中,我们定义了一个名为sendHttpRequest的异步函数,它使用 Fetch API 来发出 HTTP 请求。你需要提供 URL、HTTP 方法、请求头和请求体作为参数调用该函数。函数将返回一个 Promise,在解析响应数据后,你可以对其进行处理。
请替换示例中的 URL、方法、请求头和请求体为你实际使用的值,并根据你的需求修改和扩展代码。
原文地址: https://www.cveoy.top/t/topic/Tfx 著作权归作者所有。请勿转载和采集!