5种最流行的发送HTTP请求的方法

在这里插入图片描述
现代Javascript提供了许多向远程服务器发送HTTP请求的方法。从原生XMLHttpRequest对象到Axios等第三方库,拥有如此丰富的选择集合使得在web应用程序中请求和动态加载内容比以往任何时候都更加轻松。

所以,在今天的帖子中,我们将讨论用Javascript发送HTTP请求的不同方法。从语言提供的本地选项开始,我们将查看以下五个模块,并使用它们发送不同类型的HTTP请求。

  • XMLHttpRequest

  • Fetch

  • Axios

  • SuperAgent

  • Ky

XMLHttpRequest

XMLHttpRequest是一种Javascript原生API,它封装了发送HTTP请求的逻辑,而无需刷新已加载的网页(AJAX请求)。尽管开发人员现在很少直接使用XMLHttpRequest,但它仍然是在许多流行的HTTP请求模块下工作的构建块。

因此,了解如何使用XMLHttpRequest方法发送请求可以帮助您处理第三方库不支持的惟一用例。

下面是如何发送GET请求和使用XMLHttpRequest API从远程API异步检索数据:

//create XMLHttpRequest object
const xhr = new XMLHttpRequest()
//open a get request with the remote server URL
xhr.open("GET", "https://world.openfoodfacts.org/category/pastas/1.json")
//send the Http request
xhr.send()

//EVENT HANDLERS

//triggered when the response is completed
xhr.onload = function() {
  if (xhr.status === 200) {
    //parse JSON datax`x
    data = JSON.parse(xhr.responseText)
    console.log(data.count)
    console.log(data.products)
  } else if (xhr.status === 404) {
    console.log("No records found")
  }
}

//triggered when a network-level error occurs with the request
xhr.onerror = function() {
  console.log("Network error occurred")
}

//triggered periodically as the client receives data
//used to monitor the progress of the request
xhr.onprogress = function(e) {
  if (e.lengthComputable) {
    console.log(`${e.loaded} B of ${e.total} B loaded!`)
  } else {
    console.log(`${e.loaded} B loaded!`)
  }
}

正如这个示例所示,使用XMLHttpRequest发送GET请求的过程包括三个步骤:

  1. Create XMLHttpRequest

  2. Opening the HTTP request of the indented type

  3. Sending the request

一旦请求被发送,我们就可以使用XMLHttpObject提供的事件处理程序来处理它的响应。在这里,我们使用了两个事件处理程序:onload、onerror和onprogress。这里需要注意的是,onerror方法只处理与请求相关的网络级错误。为了识别HTTP错误,我们必须检查onload方法中的HTTP状态代码。

我们可以按照类似的模式使用XMLHttpRequest发送POST请求。

// create XMLHttpRequest object
const xhr = new XMLHttpRequest()
// open a POST request
xhr.open("POST", "/food")
// set content-type header to JSON
xhr.setRequestHeader("Content-Type", "application/json");
// send JSON data to the remote server
xhr.send(JSON.stringify(food))

// Event Handlers

// track data upload progress
xhr.upload.onprogress = function(e) {
  console.log(`${e.loaded}B of ${e.total}B uploaded!`)
}

// triggered when data upload is finished
xhr.upload.onload = function(e) {
  console.log("Upload completed")
}

// triggered when the response is fully received
xhr.onload = function() {
  console.log(xhr.status)
}

// triggered due to a network-level error
xhr.onerror = function() {
  console.log("Network error occurred")
}

早期的GET和当前的POST请求之间的一个主要区别是在发布JSON数据时显式设置内容类型头。此外,与GET请求相比,POST请求还可以触发另一种事件类型。它们是通过xhr访问的上传事件。上传字段。当请求体必须携带大量数据(如图像、文件等)时,这些事件处理程序帮助我们跟踪数据上传进度。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程轨迹_

期望和你分享一杯咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值