使用 XMLHttpRequest:
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data');
xhr.onload = () => {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
};
xhr.onerror = () => {
console.error('发生了错误');
};
xhr.send();
使用 axios:
axios.get('/api/data')
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
使用 fetch:
fetch('/api/data')
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
注意在 Node.js 环境下使用 axios 或 fetch 需要先安装相应的包。