使用 JavaScript 发出 HTTP 请求的一种常见方法是使用内置的 XMLHttpRequest 对象或 fetch 函数。在 GPT-3.5 Turbo 版本中,以下是一个使用 fetch 函数发送 HTTP 请求的示例:

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

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}

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

sendHttpRequest(url, method, headers, body)
  .then(responseData => {
    console.log('Response:', responseData);
  })
  .catch(error => {
    console.error('Error:', error);
  });

上述代码使用 fetch 函数发送了一个 POST 请求到指定的 URL,并传递了请求头和请求体。请注意,这是一个基本示例,你可以根据实际需求进行调整。

JavaScript HTTP 请求发送指南:使用 fetch 函数

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

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