javascript 请求_这是用JavaScript发出HTTP请求的最流行的方法

javascript 请求

JavaScript has great modules and methods to make HTTP requests that can be used to send or receive data from a server side resource. In this article, we are going to look at a few popular ways to make HTTP requests in JavaScript.

JavaScript具有出色的模块和方法来发出HTTP请求,这些请求可用于从服务器端资源发送或接收数据。 在本文中,我们将介绍几种在JavaScript中发出HTTP请求的流行方法。

阿贾克斯 (Ajax)

Ajax is the traditional way to make an asynchronous HTTP request. Data can be sent using the HTTP POST method and received using the HTTP GET method. Let’s take a look and make a GET request. I’ll be using JSONPlaceholder, a free online REST API for developers that returns random data in JSON format.

Ajax是发出异步HTTP请求的传统方式。 可以使用HTTP POST方法发送数据,并使用HTTP GET方法接收数据。 让我们看一下并发出GET请求。 我将使用JSONPlaceholder,这是供开发人员使用的免费在线REST API,它以JSON格式返回随机数据。

To make an HTTP call in Ajax, you need to initialize a new XMLHttpRequest() method, specify the URL endpoint and HTTP method (in this case GET). Finally, we use the open() method to tie the HTTP method and URL endpoint together and call the send() method to fire off the request.

要在Ajax中进行HTTP调用,您需要初始化一个新的XMLHttpRequest()方法,指定URL端点和HTTP方法(在本例中为GET)。 最后,我们使用open()方法将HTTP方法和URL端点绑定在一起,并调用send()方法触发请求。

We log the HTTP response to the console by using the XMLHTTPRequest.onreadystatechange property which contains the event handler to be called when the readystatechanged event is fired.

我们使用XMLHTTPRequest.onreadystatechange属性将HTTP响应记录到控制台,该属性包含在触发readystatechanged事件时要调用的事件处理程序。

const Http = new XMLHttpRequest();
const url='https://jsonplaceholder.typicode.com/posts';
Http.open("GET", url);
Http.send();

Http.onreadystatechange = (e) => {
  console.log(Http.responseText)
}

If you view your browser console, it will return an Array of data in JSON format. But how would we know if the request is done? In other words, how we can handle the responses with Ajax?

如果您查看浏览器控制台,它将返回JSON格式的数据数组。 但是我们怎么知道请求是否完成? 换句话说,我们如何使用Ajax处理响应?

The onreadystatechange property has two methods, readyState and status which allow us to check the state of our request.

onreadystatechange属性具有两种方法, readyStatestatus ,它们使我们能够检查请求的状态。

If readyState is equal to 4, it means the request is done. The readyState property has 5 responses. Learn more about it here.

如果readyState等于4,则表示请求已完成。 readyState属性有5个响应。 在此处了解更多信息。

Apart from directly making an Ajax call with JavaScript, there are other more powerful methods of making an HTTP call such as $.Ajax which is a jQuery method. I’ll discuss those now.

除了直接使用JavaScript进行Ajax调用外,还有其他更强大的HTTP调用方法,例如$.Ajax ,这是一种jQuery方法。 我现在讨论。

jQuery方法 (jQuery methods)

jQuery has many methods to easily handle HTTP requests. In order to use these methods, you’ll need to include the jQuery library in your project.

jQuery有许多方法可以轻松处理HTTP请求。 为了使用这些方法,您需要在项目中包括jQuery库。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$ .ajax ($.ajax)

jQuery Ajax is one of the simplest methods to make an HTTP call.

jQuery Ajax是进行HTTP调用的最简单方法之一。

The $.ajax method takes many parameters, some of which are required and others optional. It contains two callback options success and error to handle the response received.

$ .ajax方法采用许多参数,其中一些是必需的,而其他则是可选的。 它包含两个回调选项successerror以处理收到的响应。

$ .get方法 ($.get method)

The $.get method is used to execute GET requests. It takes two parameters: the endpoint and a callback function.

$ .get方法用于执行GET请求。 它具有两个参数:端点和回调函数。

$ .post ($.post)

The $.post method is another way to post data to the server. It take three parameters: the url, the data you want to post, and a callback function.

$.post方法是将数据发布到服务器的另一种方法。 它包含三个参数: url ,要发布的数据和一个回调函数。

$ .getJSON ($.getJSON)

The $.getJSON method only retrieves data that is in JSON format. It takes two parameters: the url and a callback function.

$.getJSON方法仅检索JSON格式的数据。 它带有两个参数: url和回调函数。

jQuery has all these methods to request for or post data to a remote server. But you can actually put all these methods into one: the $.ajax method, as seen in the example below:

jQuery具有所有这些方法来请求数据或将数据发布到远程服务器。 但是实际上您可以将所有这些方法合而为一: $.ajax方法,如以下示例所示:

(fetch)

fetch is a new powerful web API that lets you make asynchronous requests. In fact, fetch is one of the best and my favorite way to make an HTTP request. It returns a “Promise” which is one of the great features of ES6. If you are not familiar with ES6, you can read about it in this article. Promises allow us to handle the asynchronous request in a smarter way. Let’s take a look at how fetch technically works.

fetch是一种功能强大的新Web API,可让您发出异步请求。 实际上, fetch是提出HTTP请求的最好的也是我最喜欢的方法之一。 它返回一个“承诺”,这是ES6的重要功能之一。 如果你不熟悉ES6,你可以阅读一下这个文章。 承诺使我们能够以更智能的方式处理异步请求。 让我们看一下技术上的fetch方式。

The fetch function takes one required parameter: the endpoint URL. It also has other optional parameters as in the example below:

fetch功能采用一个必需的参数: endpoint URL。 它还具有其他可选参数,如下例所示:

As you can see, fetch has many advantages for making HTTP requests. You can learn more about it here. Additionally, within fetch there are other modules and plugins that allow us to send and receive a request to and from the server side, such as axios.

如您所见, fetch存在发出HTTP请求方面具有许多优势。 您可以在此处了解更多信息。 另外,在fetch中,还有其他模块和插件,例如axios ,它们使我们能够向服务器端发送请求或从服务器端接收请求。

Axios (Axios)

Axios is an open source library for making HTTP requests and provides many great features. Let’s have a look at how it works.

Axios是一个用于发出HTTP请求的开源库,并提供许多出色的功能。 让我们看看它是如何工作的。

用法: (Usage:)

First, you’d need to include Axios. There are two ways to include Axios in your project.

首先,您需要包括Axios。 有两种方法可以在项目中包含Axios。

First, you can use npm:

首先,您可以使用npm:

npm install axios --save

Then you’d need to import it

然后,您需要导入它

import axios from 'axios'

Second, you can include axios using a CDN.

其次,您可以使用CDN包含axios。

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
用axios发出请求: (Making a Request with axios:)

With Axios you can use GET and POST to retrieve and post data from the server.

借助Axios,您可以使用GETPOST从服务器检索和发布数据。

得到: (GET:)

axios takes one required parameter, and can take a second optional parameter too. This takes some data as a simple query.

axios采用一个必需参数,也可以采用第二个可选参数。 这需要一些数据作为简单查询。

开机自检: (POST:)

Axios returns a “Promise.” If you’re familiar with promises, you probably know that a promise can execute multiple requests. You can do the same thing with axios and run multiple requests at the same time.

Axios返回“承诺”。 如果您熟悉诺言,您可能知道诺言可以执行多个请求。 您可以使用axios做同样的事情,并同时运行多个请求。

Axios supports many other methods and options. You can explore them here.

Axios支持许多其他方法和选项。 您可以在这里进行探索。

Angular HttpClient (Angular HttpClient)

Angular has its own HTTP module that works with Angular apps. It uses the RxJS library to handle asynchronous requests and provides many options to perform the HTTP requests.

Angular有自己的HTTP模块,可与Angular应用程序一起使用。 它使用RxJS库处理异步请求,并提供许多选项来执行HTTP请求。

使用Angular HttpClient调用服务器 (Making a call to the server using the Angular HttpClient)

To make a request using the Angular HttpClient, we have to run our code inside an Angular app. So I created one. If you’re not familiar with Angular, check out my article, learn how to create your first Angular app in 20 minutes.

要使用Angular HttpClient发出请求,我们必须在Angular应用程序中运行代码。 所以我创建了一个。 如果您不熟悉Angular,请查看我的文章, 了解如何在20分钟内创建第一个Angular应用

The first thing we need to do is to import HttpClientModule in app.module.ts

我们需要做的第一件事是在app.module.ts导入HttpClientModule

Then, we have to create a service to handle the requests. You can easily generate a service using Angular CLI.

然后,我们必须创建一个服务来处理请求。 您可以使用Angular CLI轻松生成服务。

ng g service  FetchdataService

Then, we need to import HttpClient in fetchdataService.ts service and inject it inside the constructor.

然后,我们需要在fetchdataService.ts服务中导入HttpClient并将其注入构造函数中。

And in app.component.ts import fetchdataService

并在app.component.ts导入fetchdataService

//import
import { FetchdataService } from './fetchdata.service';

Finally, call the service and run it.

最后,调用服务并运行它。

app.component.ts:

app.component.ts:

You can check out the demo example on Stackblitz.

您可以在Stackblitz上查看演示示例。

结语 (Wrapping Up)

We’ve just covered the most popular ways to make an HTTP call request in JavaScript.

我们刚刚介绍了使用JavaScript发出HTTP调用请求的最流行方法。

Thank you for your time. If you like it, clap up to 50, click follow, and reach out to me on Twitter.

感谢您的时间。 如果您喜欢,最多可以拍50个,单击“关注”,然后在Twitter上与我联系。

By the way, I’ve recently worked with a strong group of software engineers for one of my mobile applications. The organization was great, and the product was delivered very quickly, much faster than other firms and freelancers I’ve worked with, and I think I can honestly recommend them for other projects out there. Shoot me an email if you want to get in touch — said@devsdata.com.

顺便说一句,我最近与一群强大的软件工程师一起为我的一个移动应用程序工作。 该组织很棒,产品交付速度非常快,比我所合作的其他公司和自由职业者要快得多,我想我可以诚实地向他们推荐其他项目。 如果您想与我联系,请给我发送电子邮件 -said@devsdata.com

翻译自: https://www.freecodecamp.org/news/here-is-the-most-popular-ways-to-make-an-http-request-in-javascript-954ce8c95aaa/

javascript 请求

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用浏览器内置的XMLHttpRequest对象或者使用第三方库(例如axios、fetch)来发出HTTP请求。下面是使用XMLHttpRequest对象发出GET请求的示例代码: ```javascript const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://example.com/api/data'); xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.log('请求失败。'); } }; xhr.send(); ``` 如果需要发送POST请求,需要设置请求头和请求体: ```javascript const xhr = new XMLHttpRequest(); xhr.open('POST', 'https://example.com/api/data'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.log('请求失败。'); } }; const data = { name: 'John', age: 30 }; xhr.send(JSON.stringify(data)); ``` 使用第三方库发送HTTP请求的示例代码: 使用axios库: ```javascript axios.get('https://example.com/api/data') .then(function(response) { console.log(response.data); }) .catch(function(error) { console.log(error); }); axios.post('https://example.com/api/data', { name: 'John', age: 30 }) .then(function(response) { console.log(response.data); }) .catch(function(error) { console.log(error); }); ``` 使用fetch函数: ```javascript fetch('https://example.com/api/data', { method: 'GET', headers: { 'Content-Type': 'application/json' } }) .then(function(response) { if (response.ok) { return response.json(); } else { throw new Error('请求失败。'); } }) .then(function(data) { console.log(data); }) .catch(function(error) { console.log(error); }); fetch('https://example.com/api/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'John', age: 30 }) }) .then(function(response) { if (response.ok) { return response.json(); } else { throw new Error('请求失败。'); } }) .then(function(data) { console.log(data); }) .catch(function(error) { console.log(error); }); ``` 以上代码仅供参考,具体实现需要根据具体场景进行调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值