JavaScript 发送 HTTP 请求:使用 Fetch API
使用 JavaScript 发送 HTTP 请求有多种方法,以下是一种使用现代浏览器中提供的fetch函数的示例:
// 使用fetch函数发送GET请求
fetch('http://example.com/api/data')
.then(response => response.json())
.then(data => {
// 处理返回的数据
console.log(data);
})
.catch(error => {
// 处理错误
console.error(error);
});
// 使用fetch函数发送POST请求
fetch('http://example.com/api/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => {
// 处理返回的数据
console.log(data);
})
.catch(error => {
// 处理错误
console.error(error);
});
上述代码使用fetch函数发送GET和POST请求。在GET请求中,我们使用.then在响应返回后处理JSON格式的数据。在POST请求中,我们指定了请求方法、请求头和请求体,并使用.then处理响应的JSON数据。在两种情况下,我们使用.catch捕获任何错误并进行处理。
请注意,上述代码在Web浏览器中运行,如果你在其他环境中使用JavaScript,如Node.js,则需要使用其他库或模块来发出HTTP请求,例如axios或http模块。
原文地址: https://www.cveoy.top/t/topic/RLd 著作权归作者所有。请勿转载和采集!