前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >5种最流行的发送HTTP请求的方法

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

作者头像
前端修罗场
发布2023-10-07 19:09:56
2970
发布2023-10-07 19:09:56
举报
文章被收录于专栏:Web 技术Web 技术

现代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异步检索数据:

代码语言:javascript
复制
//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请求。

代码语言:javascript
复制
// 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访问的上传事件。上传字段。当请求体必须携带大量数据(如图像、文件等)时,这些事件处理程序帮助我们跟踪数据上传进度。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • XMLHttpRequest
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档