JavaScript 发出 HTTP 请求:fetch() 函数示例
使用 JavaScript 发出 HTTP 请求的方法有多种,以下是使用现代浏览器提供的内置'fetch()'函数的示例代码:
// 在浏览器中使用 fetch() 函数发送 GET 请求
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data); // 处理返回的数据
})
.catch(error => {
console.log('发生错误:', error);
});
// 在浏览器中使用 fetch() 函数发送 POST 请求
fetch('https://api.example.com/endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' }) // 请求体的数据
})
.then(response => response.json())
.then(data => {
console.log(data); // 处理返回的数据
})
.catch(error => {
console.log('发生错误:', error);
});
请注意,此代码在现代浏览器中运行良好,但在某些旧版本的浏览器中可能不被支持。在这种情况下,您可以考虑使用类似'XMLHttpRequest'的其他 HTTP 请求库或框架(如'axios'、'jQuery.ajax'等)。
希望这能帮到您!
原文地址: https://www.cveoy.top/t/topic/HXE 著作权归作者所有。请勿转载和采集!