JavaScript中怎么发出HTTP请求

发布时间:2021-07-01 17:34:26 作者:Leah
来源:亿速云 阅读:377

这篇文章给大家介绍JavaScript中怎么发出HTTP请求,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

XMLHttpRequest

XMLHttpRequest对象可用于从Web服务器请求数据。它是这次比较中最早的方法,尽管其他选择都优于它,但由于其向后兼容性和成熟度,它仍然有效且有用。

得到:

var req= new XMLHttpRequest();//The onreadystatechange property //specifies a function to be //executed every time the status //of the XMLHttpRequest changes req.onreadystatechange = function() {     if (this.readyState == 4 &&this.status == 200) {        //The responseText property        //returns a text string                  console.log(xhttp.responseText)        //Do some stuff     } };req.open("GET", "http://dataserver/users", true); req.send();

发送:

varformData = new FormData(); formData.append("name", "Murdock"); var req = new XMLHttpRequest(); req.open("POST", "http://dataserver/update"); req.send(formData);

优点:

缺点:

Qwest

Qwest是一个基于Promise的简单ajax库,它支持XmlHttpRequest2的独立数据,例如ArrayBuffer,Blob和FormData。

得到:

qwest.get('http://dataserver/data.json')      .then(function(xhr, response) {         // ...do some stuff whith data      });

发送:

qwest.post('http://dataserver/update',{         firstname: 'Murdock',               age: 30      })      .then(function(xhr, response) {         // Make some useful actions      })      .catch(function(e, xhr, response) {         // Process the error      });

优点:

缺点:

JQuery.ajax

该库在不久前被广泛用于发出HTTP异步请求。jQuery的所有Ajax方法都返回XMLHTTPRequest对象的超集

得到:

$.ajax({     url: 'http://dataserver/data.json'   }).done(function(data) {     // ...do some stuff whith data   }).fail(function() {     // Handle error });

发送:

$.ajax({   type: "POST",   url: 'http://dataserver/update',   data: data,   success: successCallBack,   error: errorCallBack,   dataType: dataType });

优点:

缺点:

Axios

JavaScript中怎么发出HTTP请求
图源:unsplash

基于Promise的HTTP库,用于在浏览器和Nodejs上执行HTTP请求。

得到:

axios({   url: 'http://dataserver/data.json',   method: 'get' })

发送:

axios.post('http://dataserver/update',{     name: 'Murdock'   })   .then(function (response) {     console.log(response);   })   .catch(function (error) {     console.log(error);   });

优点:

缺点:

SuperAgent

SuperAgent是ajax API,旨在提供灵活性,可读性和较低的学习曲线。它也可以与Node.js一起使用。

得到:

request('GET','http://dataserver/data.json').then( success, failure);

.query()方法接受对象,这些对象与GET方法一起使用时将形成查询字符串。以下代码将产生路径/ dataserver / search?name =  Manny&lastName = Peck&order = desc。

request    .get('/dataserver/search')    .query({ name: 'Templeton' })    .query({ lastname: 'Peck' })    .query({ order: 'desc' })    .then(res => {console.dir(res)} });

发送:

request    .post('http://dataserver/update')    .send({ name: 'Murdock' })    .set('Accept', 'application/json')    .then(res => {       console.log('result' +JSON.stringify(res.body));    });

优点:

缺点:

JavaScript中怎么发出HTTP请求
图源:unsplash

Http-client

Http-client允许使用JavaScript的访存API组成HTTP客户端。

得到:

//usingES6 modules import { createFetch, base, accept, parse } from 'http-client'const fetch =createFetch(  base('http://dataserver/data.json'),    accept('application/json'),       parse('json')                      )fetch('http://dataserver/data.json').then(response => {   console.log(response.jsonData) })

发送:

//usingES6 modules import { createFetch, method, params } from 'http-client'const fetch =createFetch(   params({ name: 'Murdock' }),   base('http://dataserver/update') )

优点:

缺点:

Fetch

Fetch是原生浏览器API,用于发出替代XMLHttpRequest的请求。与XMLHttpRequest相比,Fetch使网络请求更容易。Fetch  API使用Promises避免XMLHttpRequest回调地狱。

得到:

//WithES6 fetch fetch('http://dataserver/data.json')   .then(data => {     // ...do some stuff whith data   }).catch(error => {     // Handle error });

发送:

fetch('http://dataserver/update',{   method: 'post',   headers: {     'Accept': 'application/json,text/plain, */*',     'Content-Type': 'application/json'   },   body: JSON.stringify({name: 'Murdock'}) }).then(res=>res.json())   .then(res => console.log(res));//ORwith ES2017 for example(async () => {     const response = awaitfetch('http://dataserver/update', {     method: 'POST',     headers: {       'Accept': 'application/json',       'Content-Type': 'application/json'     },     body:JSON.stringify({name='Murdock'})   });const result = awaitresponse.json();console.log(result); })();

优点:

缺点:

Fetch是一个新标准,新版本的Chrome和Firefox无需使用任何其他库就可支持它。

此外,Axios,SuperAgent或其他库都有适合的文档,易于使用,并且学习曲线不太高。在某些情况下,它们可以提供Fetch不具有的功能。

Fetch在JavaScript里是原生的,足以满足项目需求。如果没有特殊需求,我认为Fetch就是最合适的选择。

关于JavaScript中怎么发出HTTP请求就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. https协议中,不能包含http请求
  2. HTTP协议(6)HTTP请求方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

javascript http

上一篇:Java中有哪些修饰符关键词

下一篇:Javascript中Hoisting的作用是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》