js普通ajax数据请求和axios请求数据代码及总结
warning:
这篇文章距离上次修改已过441天,其中的内容可能已经有所变动。
在JavaScript中,我们可以使用原生的XMLHttpRequest对象或者更现代的fetchAPI来进行HTTP请求。而axios是一个基于Promise的HTTP客户端,它在Node.js和浏览器中都可以使用,并且它比起原生的XMLHttpRequest或fetchAPI提供了更多的特性和更简洁的语法。
- 使用原生的
XMLHttpRequest对象发送请求:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json);
}
};
xhr.send();- 使用
fetchAPI发送请求:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));- 使用
axios发送请求:
首先,你需要安装axios库,可以通过npm或者yarn进行安装:
npm install axios
# 或者
yarn add axios然后,你可以使用以下代码进行数据请求:
const axios = require('axios');
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error:', error);
});总结:
XMLHttpRequest和fetch是原生JavaScript提供的API,而axios是一个第三方库。axios基于Promise,使得异步处理更加简洁,而且它支持浏览器和Node.js。axios在服务器端和客户端都可以使用,并且它可以自动转换JSON数据。fetch是现代的API,而axios提供了更多的功能,例如可以通过axios.create()方法配置默认的选项。
评论已关闭