原生js创建get/post请求以及封装方式、axios的基本使用
原生JavaScript创建GET和POST请求通常使用XMLHttpRequest
对象。以下是简单的封装方法:
function httpGet(url, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function httpPost(url, data, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
};
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(data);
}
使用方法:
httpGet('https://api.example.com/data', function(response) {
console.log(response);
});
httpPost('https://api.example.com/data', 'key1=value1&key2=value2', function(response) {
console.log(response);
});
对于现代开发,推荐使用fetch
API,它提供了更现代的异步JavaScript HTTP请求的方式。
使用fetch
的GET请求示例:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
使用fetch
的POST请求示例:
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key1: 'value1', key2: 'value2' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
axios
是一个基于Promise
的HTTP客户端,它也可以用来发送请求。
安装axios
:
npm install axios
使用axios
发送GET请求:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error:', error);
});
使用axios
发送POST请求:
axios.post('https://api.example.com/data', {
key1: 'value1',
key2: 'value2'
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error:', error);
});
axios
在服务器端也很流行,并支持Node.js。在Node.js环境下,你可以使用axios
发送请求,类似于浏览器端的用法。
评论已关闭