JavaScript 中进行 HTTP 请求

使用 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 需要先安装相应的包。

猜你喜欢

转载自blog.csdn.net/weixin_42602736/article/details/130870867