使用 JavaScript 发起 HTTP 请求可以使用内置的 XMLHttpRequest 对象或者使用第三方库,如 Axios 或 Fetch。

使用 XMLHttpRequest 对象的示例代码如下:

// 创建一个新的 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();

// 设置请求方法和 URL
xhr.open('GET', 'https://api.example.com/data', true);

// 设置请求头(可选)
xhr.setRequestHeader('Content-Type', 'application/json');

// 监听请求状态变化
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    // 请求成功
    var response = JSON.parse(xhr.responseText);
    console.log(response);
  }
};

// 发送请求
xhr.send();

使用 Axios 库的示例代码如下:

// 安装 Axios 库:npm install axios

// 导入 Axios
var axios = require('axios');

// 发送 GET 请求
axios.get('https://api.example.com/data')
  .then(function(response) {
    // 请求成功
    console.log(response.data);
  })
  .catch(function(error) {
    // 请求失败
    console.log(error);
  });

使用 Fetch API 的示例代码如下:

// 发送 GET 请求
fetch('https://api.example.com/data')
  .then(function(response) {
    if (response.ok) {
      // 请求成功
      return response.json();
    }
    throw new Error('Network response was not ok.');
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    // 请求失败
    console.log(error);
  });

以上是基本的示例代码,可以根据实际需求进行进一步的配置和处理。请注意,示例中的 URL 和请求头需要根据你的实际情况进行替换。

JavaScript 发起 HTTP 请求:XMLHttpRequest、Axios 和 Fetch API

原文地址: http://www.cveoy.top/t/topic/zti 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录