JavaScript HTTP 请求:使用 fetch 发送 GET 和 POST 请求
在 JavaScript 中,你可以使用内置的 fetch 函数来发出 HTTP 请求。下面是一个示例:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// 处理返回的数据
console.log(data);
})
.catch(error => {
// 处理错误
console.error(error);
});
在上面的示例中,我们使用 fetch 函数发送了一个 GET 请求到 https://api.example.com/data 地址。然后,我们使用 .then 方法来处理返回的响应数据,使用 .catch 方法来处理可能的错误。
你还可以添加其他的请求选项,例如设置请求方法、请求头、请求体等。以下是一个使用 POST 请求的示例:
fetch('https://api.example.com/data', {
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);
});
以上示例中,我们设置了请求方法为 POST,并添加了请求头 Content-Type: application/json。同时,我们通过 JSON.stringify 将一个 JSON 对象转换为字符串,并将其作为请求体发送。
请根据你的具体需求,使用适当的请求选项和处理方法来发出 HTTP 请求。
原文地址: https://www.cveoy.top/t/topic/qwW 著作权归作者所有。请勿转载和采集!