ajax请求头怎么设置 ajax和http请求的区别

我被授权翻译丹尼马尔科夫的原作。在本教程中,我们将学习如何使用JS进行AJAX调用。1。AJAX术语AJAX意味着异步JavaScript和XML。AJAX在JS中用于发出异步网络请求以获取资源。当然,与名字所暗示的不同,资源并不局限于XML,还可以用来获取JSON、HTML或纯文本等资源。有许多方...

我被授权翻译丹尼·马尔科夫的原作。

在本教程中,我们将学习如何使用JS进行AJAX调用。

1。AJAX

术语AJAX意味着异步JavaScript和XML

AJAX在JS中用于发出异步网络请求以获取资源。当然,与名字所暗示的不同,资源并不局限于XML,还可以用来获取JSON、HTML或纯文本等资源。

有许多方法可以发出网络请求并从服务器获取数据。我们将一一介绍。

2。XMLHttpRequest

XMLHttpRequest对象(称为XHR)以前用于从服务器异步检索数据。

使用XML是因为它首先用于检索XML数据。现在,它还可以用来检索JSON、HTML或纯文本。

示例2.1: GET

function success() { var data = JSON.parse(this.responseText) console.log(data)}function error (err) { console.log('Error Occurred:', err)}var xhr = new XMLHttpRequest()xhr.onload = successxhr.onerror = errorxhr.open("GET", ""https://jsonplaceholder.typicode.com/posts/1")xhr.send()

我们看到,要发出一个简单的GET请求,需要两个侦听器来处理请求的成功和失败。我们还需要调用open()和send()方法。来自服务器的响应存储在responseText变量中,该变量使用JSON.parse()转换为JavaScript对象。

function success() { var data = JSON.parse(this.responseText); console.log(data);}function error(err) { console.log('Error Occurred :', err);}var xhr = new XMLHttpRequest();xhr.onload = success;xhr.onerror = error;xhr.open("POST", "https://jsonplaceholder.typicode.com/posts");xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");xhr.send(JSON.stringify({ title: 'foo', body: 'bar', userId: 1 }));

我们看到POST请求类似于GET请求。我们需要使用setRequestHeader额外设置请求头“Content-Type ”,并在send方法中使用JSON.stringify将JSON正文作为字符串发送。

2.3 XMLHttpRequest vs Fetch

早期的开发人员已经使用XMLHttpRequest请求数据很多年了。现代的fetch API允许我们发出类似于XMLHttpRequest(XHR)的网络请求。主要区别在于fetch()API使用了Promises,使得API更加简单简洁,避免了回调到地狱。

3。提取API

Fetch是一个用于AJAX调用的本地JavaScript API。它已被大多数浏览器支持,现在被广泛使用。

3.1 API用法

fetch(url, options) .then(response => { // handle response data }) .catch(err => { // handle errors });

API参数

fetch() API有两个参数

url

是必填参数,它是您要获取的资源的路径。options是一个可选参数。不需要提供这个参数来发出简单的GET请求。method: GET | POST | PUT | DELETE | PATCHheaders: 请求头,如 { “Content-type”: “application/json; charset=UTF-8” }mode: cors | no-cors | same-origin | navigatecache: default | reload | no-cachebody: 一般用于POST请求

API返回Promise对象

fetch() API返回一个promise对象。

如果存在网络错误,则将拒绝,这会在.catch()块中处理。如果来自服务器的响应带有任何状态码(如200、404、500),则promise将被解析。响应对象可以在.then()块中处理。

错误处理

请注意,对于一个成功的响应,我们期望状态代码是200(正常状态),但是即使响应有错误状态代码(比如404(未找到资源)和500(内部服务器错误)),fetch() API的状态是解析的,我们需要在。then()块。

我们可以在响应对象中看到HTTP状态:

HTTP状态码,例如200。ok –布尔值,如果HTTP状态代码为200-299,则为true。

3.3示例:GET

const getTodoItem = fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .catch(err => console.error(err));getTodoItem.then(response => console.log(response));Response { userId: 1, id: 1, title: "delectus aut autem", completed: false }

在上面的代码中有两点需要注意:

fetch API返回一个promise对象,我们可以将其分配给变量并稍后执行。我们还必须调用response.json()将响应对象转换为JSON

错误处理

让我们看看当HTTP GET请求抛出500错误时会发生什么:

fetch('http://httpstat.us/500') // this API throw 500 error .then(response => () => { console.log("Inside first then block"); return response.json(); }) .then(json => console.log("Inside second then block", json)) .catch(err => console.error("Inside catch block:", err));Inside first then block? ? Inside catch block: SyntaxError: Unexpected token I in JSON at position 4

我们看到,即使API抛出500错误,它仍然会先进入then()块,在这里它无法解析错误JSON,抛出catch()块捕捉到的错误。

这意味着如果我们使用fetch()API,我们需要显式地处理这样的错误

fetch('http://httpstat.us/500') .then(handleErrors) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error("Inside catch block:", err));function handleErrors(response) { if (!response.ok) { // throw error based on custom conditions on response throw Error(response.statusText); } return response;} ? Inside catch block: Error: Internal Server Error at handleErrors (Script snippet %239:9)

3.3示例:POST

fetch('https://jsonplaceholder.typicode.com/todos', { method: 'POST', body: JSON.stringify({ completed: true, title: 'new todo item', userId: 1 }), headers: { "Content-type": "application/json; charset=UTF-8" } }) .then(response => response.json()) .then(json => console.log(json)) .catch(err => console.log(err))Response? {completed: true, title: "new todo item", userId: 1, id: 201}

在上面的代码中需要注意两件事

POST请求类似于GET请求。我们还需要在fetch() API的第二个参数中发送method,body 和headers 属性。我们必须需要使用 JSON.stringify() 将对象转成字符串请求body参数

4。Axios API

Axios API与fetch API非常相似,但有一些改进。就个人而言,我更喜欢使用Axios API而不是fetch() API,原因如下:

为GET 请求提供 axios.get(),为 POST 请求提供 axios.post()等提供不同的方法,这样使我们的代码更简洁。将响应代码(例如404、500)视为可以在catch()块中处理的错误,因此我们无需显式处理这些错误。它提供了与IE11等旧浏览器的向后兼容性它将响应作为JSON对象返回,因此我们无需进行任何解析

4.1示例:GET

// 在chrome控制台中引入脚本的方法var script = document.createElement('script');script.type = 'text/javascript';script.src = 'https://unpkg.com/axios/dist/axios.min.js';document.head.appendChild(script);axios.get('https://jsonplaceholder.typicode.com/todos/1') .then(response => console.log(response.data)) .catch(err => console.error(err));Response{ userId: 1, id: 1, title: "delectus aut autem", completed: false }

我们可以看到,我们直接使用response来获取响应数据。与fetch() API不同,没有数据的解析对象。

错误处理

axios.get('http://httpstat.us/500') .then(response => console.log(response.data)) .catch(err => console.error("Inside catch block:", err));Inside catch block: Error: Network Error

我们看到catch()块也捕获了500个错误,不像fetch() API,我们必须显式地处理它们。

4.2示例:POST

axios.post('https://jsonplaceholder.typicode.com/todos', { completed: true, title: 'new todo item', userId: 1 }) .then(response => console.log(response.data)) .catch(err => console.log(err)) {completed: true, title: "new todo item", userId: 1, id: 201}

我们看到POST方法很短,可以直接传递请求体参数,和fetch()API不同。

本文来自扎女孩的小辫子投稿,不代表舒华文档立场,如若转载,请注明出处:https://www.chinashuhua.cn/24/477857.html

打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
() 0
上一篇 03-27
下一篇 03-27

相关推荐

  • 进入路由器设置页面 电脑进入路由器设置界面

    1。连接线将运营商的宽带网线连接到路由器的WAN口或WAN/LAN口。线路连接后,如果WAN口对应的指示灯不亮,说明线路连接有问题。请检查以确保网络电缆连接牢固,或者尝试更换另一根网络电缆。2。设置路由器上网(1)查看路由器底部标签上的路由器出厂监听信号名称。(2)打开定位器

    2023-07-29 08:52:01
    206 0
  • chrome更改语言设置 教你设置谷歌浏览器的语言

    Google Chrome是由Google开发的一款设计简单、高效的Web浏览工具。Google Chrome的特点是简洁、快速。GoogleChrome支持多标签浏览,每个标签页面都在独立的“沙箱”内运行,在提高安全性的同时,一个标签页面的崩溃也不会导致其他标签页面被关闭。此外,Google Chrome基于更强

    2023-07-29 08:32:01
    268 0
  • 高德地图怎么设置3d实景导航(高德地图怎么设置语音播报声音)

    【高德地图怎么设置3d实景导航】核心答案要点:高德地图设置3d实景导航需要在步行导航中进行设置。以手机华为p40为例,高德地图设置3d实景导航的步骤分为3步,具体操作如下: 高德地图设置3d实景导航需要在步行导航中进行设置。以手机华为p40为例,高德地图设置3d实景导航的步

    2023-07-29 07:37:01
    232 0
  • 凌派如何设置自动锁

    自动锁,也就是自动上锁凌厂没有自动锁定装置,所以没办法设置如果想有自动锁定装置,只能以后再装如果你想安装自动锁,你可以去4S商店或专业改装店S店会多花一点钱,但会比去年同期更靠谱自动锁定功能非常有用。本田凌派汽车原车不具备自动落锁的功能,需要到4S店加装才能实

    2023-07-29 03:56:01
    867 0

评论列表

联系我们

在线咨询: QQ交谈

邮件:admin@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信