JavaScript 发出 HTTP 请求:fetch() 和 axios 详解
使用 JavaScript 发出 HTTP 请求可以使用内置的 'fetch()' 函数或者使用第三方库例如 'axios'。下面是使用 'fetch()' 函数的示例代码:
// 使用 fetch() 函数发送 GET 请求
fetch('https://api.example.com/data')
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('请求失败');
}
})
.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 => {
if (response.ok) {
return response.json();
} else {
throw new Error('请求失败');
}
})
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});
如果你更喜欢使用第三方库,比如 axios,可以按照以下步骤:
- 使用 npm 安装 axios 库:
npm install axios - 在你的 JavaScript 文件中引入 axios:
const axios = require('axios');(在浏览器环境下,可以通过<script>标签引入 axios 库) - 发出 GET 请求的示例代码:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
- 发出 POST 请求的示例代码:
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/bnwn 著作权归作者所有。请勿转载和采集!