JavaScript 发起 HTTP 请求:fetch 和 axios 详解
使用 JavaScript 发起 HTTP 请求可以使用内置的 'fetch' 函数或者使用第三方库,如 'axios'。以下是使用 'fetch' 和 'axios' 两种方式的示例代码:
使用 'fetch' 函数:
fetch(url, {
method: 'GET', // 或者 'POST', 'PUT', 'DELETE', 等等
headers: {
'Content-Type': 'application/json', // 请求的数据类型
// 其他自定义的请求头部
},
// 可选的请求体数据,适用于 'POST', 'PUT', 等等
body: JSON.stringify({
key1: 'value1',
key2: 'value2'
})
})
.then(response => response.json()) // 解析响应为JSON格式
.then(data => {
// 处理响应数据
})
.catch(error => {
// 处理错误
});
使用 'axios' 库:
首先,你需要安装并导入 'axios' 库:
$ npm install axios
const axios = require('axios'); // 在Node.js环境中导入
axios.get(url, {
headers: {
'Content-Type': 'application/json', // 请求的数据类型
// 其他自定义的请求头部
},
// 可选的请求体数据,适用于 'POST', 'PUT', 等等
data: {
key1: 'value1',
key2: 'value2'
}
})
.then(response => {
const data = response.data;
// 处理响应数据
})
.catch(error => {
// 处理错误
});
请注意,以上示例仅作为参考,你还可以根据具体的需求进行调整和扩展。
原文地址: https://www.cveoy.top/t/topic/bMbh 著作权归作者所有。请勿转载和采集!