ホームページ ウェブフロントエンド CSSチュートリアル axios が Promise ベースの HTTP リクエスト クライアントを使用する方法

axios が Promise ベースの HTTP リクエスト クライアントを使用する方法

Mar 09, 2018 pm 05:09 PM
axios http promise

今回は、axios が Promise ベースの HTTP リクエスト クライアントをどのように使用するかを説明します。
axios


ブラウザとnode.jsの両方で使用できるPromiseベースのHTTPリクエストクライアント

機能

ブラウザでXMLHttpRequestsリクエストを送信

node.jsでhttpリクエストを送信

PromiseAPIをサポート

リクエストとレスポンスのインターセプト

リクエストとレスポンスのデータを変換

JSONデータを自動的に変換

npmからセキュリティを保護するためのクライアントサポート:

$ bower install axios
ログイン後にコピー

GETリクエストを送信

$ npm install axios
ログイン後にコピー

POSTリクエストを送信

// Make a request for a user with a given IDaxios.get('/user?ID=12345').then(function(response){console.log(response);}).catch(function(response){console.log(response);});
// Optionally the request above could also be done asaxios.get('/user',{params:{ID:12345}}).then(function(response){console.log(response);}).catch(function(response){console.log(response);});
ログイン後にコピー

複数の同時リクエストを送信

axios.post('/user',{firstName:'Fred',lastName:'Flintstone'}).then(function(response){console.log(response);}).catch(function(response){console.log(response);});
ログイン後にコピー

axios API

対応するパラメータをaxiosに渡すことでリクエストをカスタマイズできます:

リクエストメソッド

エイリアス

便宜上、サポートされているすべてのリクエストメソッドにエイリアスを提供しています

axios(config)
// Send a POST requestaxios({method:'post',url:'/user/12345',data:{firstName:'Fred',lastName:'Flintstone'}});
axios(url[, config])
// Sned a GET request (default method)axios('/user/12345');
ログイン後にコピー

alias メソッドを使用する場合、url、method、data 属性を構成パラメーターで指定する必要はありません。

同時実行同時リクエストを処理するためのヘルパーメソッド

axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
ログイン後にコピー

インスタンスを作成する

カスタム構成で新しい axios インスタンスを作成できます。

axios.all(iterable)
axios.spread(callback)
ログイン後にコピー

インスタンス メソッド

利用可能なすべてのインスタンス メソッドは以下にリストされており、指定された構成はインスタンスの構成とマージされます。

axios.create([config])
varinstance=axios.create({baseURL:'https://some-domain.com/api/',timeout:1000,headers:{'X-Custom-Header':'foobar'}});
ログイン後にコピー

リクエスト設定

利用可能なリクエスト設定項目は次のとおりです。URL のみが必要です。メソッドが指定されていない場合、デフォルトのリクエスト メソッドは GET です。

axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
ログイン後にコピー

レスポンス データ構造

レスポンス データには次の情報が含まれます:

{// `url` is the server URL that will be used for the requesturl:'/user',
// `method` is the request method to be used when making the requestmethod:'get',
// default// `baseURL` will be prepended to `url` unless `url` is absolute.
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
// to methods of that instance.baseURL:' 
// `transformRequest` allows changes to the request data before it is sent to the server
// This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
// The last function in the array must return a string or an ArrayBuffertransformRequest:[function(data){
// Do whatever you want to transform the datareturndata;}],
// `transformResponse` allows changes to the response data to be made before
// it is passed to then/catchtransformResponse:[function(data){
// Do whatever you want to transform the datareturndata;}],
// `headers` are custom headers to be sentheaders:{'X-Requested-With':'XMLHttpRequest'},
// `params` are the URL parameters to be sent with the requestparams:{ID:12345},
// `paramsSerializer` is an optional function in charge of serializing `params`
// (e.g. https://www.npmjs.com/package/qs,  paramsSerializer:function(params){returnQs.stringify(params,{arrayFormat:'brackets'})},
// `data` is the data to be sent as the request body// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be a string, an ArrayBuffer or a hashdata:{firstName:'Fred'},
// `timeout` specifies the number of milliseconds before the request times out.
// If the request takes longer than `timeout`, the request will be aborted.timeout:1000,
// `withCredentials` indicates whether or not cross-site Access-Control requests
// should be made using credentialswithCredentials:false,
// default// `adapter` allows custom handling of requests which makes testing easier.
// Call `resolve` or `reject` and supply a valid response (see [response docs](#response-api)).adapter:function(resolve,reject,config){/* ... */},
// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
// This will set an `Authorization` header, overwriting any existing
// `Authorization` custom headers you have set using `headers`.auth:{username:'janedoe',password:'s00pers3cret'}
// `responseType` indicates the type of data that the server will respond with
// options are 'arraybuffer', 'blob', 'document', 'json', 'text'responseType:'json',
// default// `xsrfCookieName` is the name of the cookie to use as a value for xsrf tokenxsrfCookieName:'XSRF-TOKEN',
// default// `xsrfHeaderName` is the name of the http header that carries the xsrf token valuexsrfHeaderName:'X-XSRF-TOKEN',
// default// `progress` allows handling of progress events for 'POST' and 'PUT uploads'
// as well as 'GET' downloadsprogress:function(progressEvent){
// Do whatever you want with the native progress event}}
ログイン後にコピー

then または catch を使用すると、次のレスポンスを受け取ります:

{// `data` is the response that was provided by the serverdata:{},
// `status` is the HTTP status code from the server responsestatus:200,
// `statusText` is the HTTP status message from the server responsestatusText:'OK',
// `headers` the headers that the server responded withheaders:{},
// `config` is the config that was provided to `axios` for the requestconfig:{}}
ログイン後にコピー

デフォルト設定

各リクエスト設定のデフォルトを指定できます。

グローバル axios のデフォルト設定

axios.get('/user/12345').then(function(response){console.log(response.data);console.log(response.status);console.log(response.statusText);console.log(response.headers);console.log(response.config);});
ログイン後にコピー

カスタム インスタンスのデフォルト設定

axios.defaults.baseURL='https:
//api.example.com';axios.defaults.headers.common['Authorization']=AUTH_TOKEN;axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded';
ログイン後にコピー

設定の優先順位

// Set config defaults when creating the instancevarinstance=axios.create({baseURL:' 
// Alter defaults after instance has been createdinstance.defaults.headers.common['Authorization']=AUTH_TOKEN;
ログイン後にコピー

インターセプター

リクエストとレスポンスを処理する前にインターセプトしてからキャッチすることができます

Config will be merged with an order of precedence. The order is library defaults found inlib
/defaults.js, thendefaultsproperty of the instance, and finallyconfigargument for the request. The latter will take precedence over the former. Here's an example.
// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the libraryvarinstance=axios.create();
// Override timeout default for the library
// Now all requests will wait 2.5 seconds before timing outinstance.defaults.timeout=2500;
// Override timeout for this request as it's known to take a long timeinstance.get('/longRequest',{timeout:5000});
ログイン後にコピー

インターセプターを削除します:

// 添加一个请求拦截器axios.interceptors.request.use(function(config){
// Do something before request is sentreturnconfig;},function(error){
// Do something with request errorreturnPromise.reject(error);});
// 添加一个响应拦截器axios.interceptors.response.use(function(response){
// Do something with response datareturnresponse;},function(error){
// Do something with response errorreturnPromise.reject(error);});
ログイン後にコピー

カスタム axios インスタンスへのインターセプター:

varmyInterceptor=axios.interceptors.request.use(function(){/*...*/});axios.interceptors.request.eject(myInterceptor);
ログイン後にコピー

この記事の事例を読んだ後は、この方法を習得したと思います。さらに興味深い情報については、PHP 中国語 Web サイトの他の関連記事に注目してください。

関連記事:

VUE で anmate.css を使用する方法

css グラデーションカラー

Vue-cli シェルフメソッドに Iview フォントアイコンが見つからない問題の解決策

以上がaxios が Promise ベースの HTTP リクエスト クライアントを使用する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

http ステータス コード 520 は何を意味しますか? http ステータス コード 520 は何を意味しますか? Oct 13, 2023 pm 03:11 PM

HTTP ステータス コード 520 は、サーバーがリクエストの処理中に不明なエラーに遭遇し、より具体的な情報を提供できないことを意味します。サーバーがリクエストを処理しているときに不明なエラーが発生したことを示すために使用されます。サーバー構成の問題、ネットワークの問題、またはその他の不明な理由が原因である可能性があります。これは通常、サーバー構成の問題、ネットワークの問題、サーバーの過負荷、またはコーディング エラーが原因で発生します。ステータス コード 520 エラーが発生した場合は、Web サイト管理者またはテクニカル サポート チームに連絡して詳細情報と支援を得ることが最善です。

Web ページのリダイレクトの一般的なアプリケーション シナリオを理解し、HTTP 301 ステータス コードを理解する Web ページのリダイレクトの一般的なアプリケーション シナリオを理解し、HTTP 301 ステータス コードを理解する Feb 18, 2024 pm 08:41 PM

HTTP 301 ステータス コードの意味を理解する: Web ページ リダイレクトの一般的なアプリケーション シナリオ インターネットの急速な発展に伴い、Web ページの操作に対する人々の要求はますます高くなっています。 Web デザインの分野では、Web ページのリダイレクトは一般的かつ重要なテクノロジであり、HTTP 301 ステータス コードによって実装されます。この記事では、HTTP 301 ステータス コードの意味と、Web ページ リダイレクトにおける一般的なアプリケーション シナリオについて説明します。 HTTP301 ステータス コードは、永続的なリダイレクト (PermanentRedirect) を指します。サーバーがクライアントのメッセージを受信すると、

約束を守る: 約束を守ることの長所と短所 約束を守る: 約束を守ることの長所と短所 Feb 18, 2024 pm 08:06 PM

日常生活では、約束と履行の間で問題に遭遇することがよくあります。個人的な関係でもビジネス取引でも、約束を守ることが信頼を築く鍵となります。ただし、コミットメントの是非についてはしばしば議論の余地があります。この記事では、約束の長所と短所を検討し、約束を守る方法についていくつかのアドバイスを提供します。約束されたメリットは明らかです。まず、コミットメントは信頼を築きます。人が約束を守るとき、その人は信頼できる人であると他人に信じ込ませます。信頼は人々の間に確立される絆であり、それは人々をより良くすることができます

HTTP 200 OK: 成功した応答の意味と目的を理解する HTTP 200 OK: 成功した応答の意味と目的を理解する Dec 26, 2023 am 10:25 AM

HTTP ステータス コード 200: 成功した応答の意味と目的を調べる HTTP ステータス コードは、サーバーの応答のステータスを示すために使用される数値コードです。このうち、ステータス コード 200 は、リクエストがサーバーによって正常に処理されたことを示します。この記事では、HTTP ステータス コード 200 の具体的な意味と使用法について説明します。まず、HTTP ステータス コードの分類を理解しましょう。ステータス コードは、1xx、2xx、3xx、4xx、5xx の 5 つのカテゴリに分類されます。このうち、2xx は成功応答を示します。 200 は 2xx で最も一般的なステータス コードです

httpリクエスト415エラーの解決策 httpリクエスト415エラーの解決策 Nov 14, 2023 am 10:49 AM

解決策: 1. リクエスト ヘッダーの Content-Type を確認する; 2. リクエスト本文のデータ形式を確認する; 3. 適切なエンコード形式を使用する; 4. 適切なリクエスト メソッドを使用する; 5. サーバー側のサポートを確認する。

Promise.resolve() について詳しく見る Promise.resolve() について詳しく見る Feb 18, 2024 pm 07:13 PM

Promise.resolve() の詳細な説明には、特定のコード例が必要です。Promise は、非同期操作を処理するための JavaScript のメカニズムです。実際の開発では、順番に実行する必要があるいくつかの非同期タスクを処理する必要があることがよくあり、満たされた Promise オブジェクトを返すために Promise.resolve() メソッドが使用されます。 Promise.resolve() は Promise クラスの静的メソッドであり、

HTTP リクエストのタイムアウトに対してどのようなステータス コードが返されますか? HTTP リクエストのタイムアウトに対してどのようなステータス コードが返されますか? Feb 18, 2024 pm 01:58 PM

HTTP リクエストがタイムアウトになり、サーバーから 504GatewayTimeout ステータス コードが返されることがよくあります。このステータス コードは、サーバーがリクエストを実行しても、リクエストに必要なリソースを取得できないか、一定時間が経過してもリクエストの処理を完了できないことを示します。これは 5xx シリーズのステータス コードで、サーバーに一時的な問題または過負荷が発生し、その結果クライアントのリクエストを正しく処理できなくなったことを示します。 HTTP プロトコルでは、さまざまなステータス コードに特定の意味と用途があり、504 ステータス コードはリクエストのタイムアウトの問題を示すために使用されます。顧客の中で

C++ を使用して HTTP ストリーミングを実装するにはどうすればよいですか? C++ を使用して HTTP ストリーミングを実装するにはどうすればよいですか? May 31, 2024 am 11:06 AM

C++ で HTTP ストリーミングを実装するにはどうすればよいですか? Boost.Asio と asiohttps クライアント ライブラリを使用して、SSL ストリーム ソケットを作成します。サーバーに接続し、HTTP リクエストを送信します。 HTTP 応答ヘッダーを受信して​​出力します。 HTTP 応答本文を受信して​​出力します。

See all articles