使用JavaScript发出HTTP请求,可以使用内置的Fetch API或XMLHttpRequest对象。以下是使用Fetch API的示例代码:

async function makeHttpRequest(url, method, body = null, headers = {}) {
  try {
    const response = await fetch(url, {
      method: method,
      body: body,
      headers: headers
    });

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error:', error);
    throw new Error('Failed to make the HTTP request.');
  }
}

// 示例用法
const url = 'https://api.example.com/endpoint';
const method = 'POST';
const body = JSON.stringify({ key: 'value' });
const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer <your_access_token>'
};

try {
  const responseData = await makeHttpRequest(url, method, body, headers);
  console.log(responseData);
} catch (error) {
  console.error(error);
}

请注意,此代码演示了使用Fetch API进行POST请求,并使用JSON作为请求体的示例。您可以根据您的实际需求进行调整。

使用XMLHttpRequest对象也可以完成类似的任务,以下是使用XMLHttpRequest的示例代码:

function makeHttpRequest(url, method, body = null, headers = {}) {
  return new Promise(function(resolve, reject) {
    const xhr = new XMLHttpRequest();
    xhr.open(method, url);

    for (const [header, value] of Object.entries(headers)) {
      xhr.setRequestHeader(header, value);
    }

    xhr.onload = function() {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve(JSON.parse(xhr.responseText));
      } else {
        reject(new Error('Failed to make the HTTP request.'));
      }
    };

    xhr.onerror = function() {
      reject(new Error('Failed to make the HTTP request.'));
    };

    xhr.send(body);
  });
}

// 示例用法
const url = 'https://api.example.com/endpoint';
const method = 'POST';
const body = JSON.stringify({ key: 'value' });
const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer <your_access_token>'
};

makeHttpRequest(url, method, body, headers)
  .then(function(responseData) {
    console.log(responseData);
  })
  .catch(function(error) {
    console.error(error);
  });

这是使用XMLHttpRequest对象进行POST请求的示例,同样使用JSON作为请求体。您也可以根据需要进行调整。

如何使用JavaScript发出HTTP请求 - Fetch API和XMLHttpRequest

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

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