JavaScript HTTP 请求: 使用 Fetch 和 Axios 发起 GET 和 POST 请求
使用 JavaScript 发出 HTTP 请求可以使用内置的 'fetch()' 函数或者第三方库(如 Axios)来实现。下面是使用原生 JavaScript 的示例代码:
// 使用 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/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.log(error));
上述代码示例中,第一个示例使用 'fetch()' 函数发出了一个 GET 请求,并在控制台打印返回的 JSON 数据。第二个示例展示了如何使用 'fetch()' 函数发出一个带有 JSON 数据的 POST 请求。你可以根据自己的需求修改 URL、请求方法、请求头和请求体等参数。
请注意,这只是一个基本示例,实际中你可能需要根据具体的 API 要求进行更多的配置和处理。
原文地址: https://www.cveoy.top/t/topic/QpJ 著作权归作者所有。请勿转载和采集!