Javascript 发出 HTTP 请求:使用 fetch 和 axios
使用 Javascript 发出 HTTP 请求可以使用内置的fetch函数或者使用第三方库例如axios。
使用内置的fetch函数可以按照以下方式发送 GET 请求:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// 处理返回的数据
console.log(data);
})
.catch(error => {
// 处理错误
console.log(error);
});
要发送 POST 请求,您可以使用fetch的method选项设置为'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);
});
如果您选择使用第三方库axios,首先需要安装它:
npm install axios
然后,您可以使用以下方式发送 GET 请求:
const axios = require('axios');
axios.get('https://api.example.com/data')
.then(response => {
// 处理返回的数据
console.log(response.data);
})
.catch(error => {
// 处理错误
console.log(error);
});
发送 POST 请求使用axios如下所示:
const axios = require('axios');
axios.post('https://api.example.com/data', { key: 'value' })
.then(response => {
// 处理返回的数据
console.log(response.data);
})
.catch(error => {
// 处理错误
console.log(error);
});
这些是使用 Javascript 发出 HTTP 请求的基本示例。您可以根据实际情况自定义请求头、参数等。
原文地址: https://www.cveoy.top/t/topic/RnX 著作权归作者所有。请勿转载和采集!