要使用 JavaScript 发出 HTTP 请求,您可以使用浏览器的内置'XMLHttpRequest'对象或'fetch'函数。以下是使用两种方法之一发出 GET 请求的示例代码:

使用 XMLHttpRequest:

function makeHttpRequest(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      callback(xhr.responseText);
    }
  };
  xhr.open('GET', url, true);
  xhr.send();
}

var apiUrl = 'https://api.example.com/data';
makeHttpRequest(apiUrl, function(response) {
  console.log(response);
});

使用 fetch:

function makeHttpRequest(url) {
  return fetch(url)
    .then(function(response) {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then(function(data) {
      console.log(data);
    })
    .catch(function(error) {
      console.error('Error:', error);
    });
}

var apiUrl = 'https://api.example.com/data';
makeHttpRequest(apiUrl);

这些示例代码可以用于浏览器环境中,但无法直接在 Node.js 环境中运行。如果您想在 Node.js 中发出 HTTP 请求,可以使用'axios'、'node-fetch'或其他类似的库来处理请求。

JavaScript HTTP 请求: 使用 XMLHttpRequest 和 Fetch 发送 GET 请求

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

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