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

今回は、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に渡すことでリクエストをカスタマイズできます:

functiongetUserAccount(){returnaxios.get('/user/12345');}functiongetUserPermissions(){returnaxios.get('/user/12345/permissions');}axios.all([getUserAccount(),getUserPermissions()]).then(axios.spread(function(acct,perms){// Both requests are now complete}));

リクエストメソッド

エイリアス

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

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 までご連絡ください。
毎週のプラットフォームニュース:Galaxy Store、Tappable Stories、CSS SubgridのWebアプリ毎週のプラットフォームニュース:Galaxy Store、Tappable Stories、CSS SubgridのWebアプリApr 14, 2025 am 11:20 AM

今週のラウンドアップ:Firefoxは錠前屋のような力を獲得し、Samsung' s Galaxy StoreがプログレッシブWebアプリをサポートし始め、CSS SubgridはFirefoxで出荷しています

毎週のプラットフォームニュース:インターネットエクスプローラーモード、検索コンソールの速度レポート、通知プロンプトの制限毎週のプラットフォームニュース:インターネットエクスプローラーモード、検索コンソールの速度レポート、通知プロンプトの制限Apr 14, 2025 am 11:15 AM

今週のラウンドアップ:Internet ExplorerがEdgeに進み、Google Search Consoleが新しい速度レポートを宣伝し、FirefoxがFacebookの通知を提供します

CSSカスタムプロパティを使用したスコープのパワー(および楽しい)CSSカスタムプロパティを使用したスコープのパワー(および楽しい)Apr 14, 2025 am 11:11 AM

おそらく、CSS変数に少なくとも少し精通しているでしょう。そうでない場合は、ここに2秒の概要があります:それらは本当にカスタムプロパティと呼ばれます、あなたは設定します

私たちはプログラマーです私たちはプログラマーですApr 14, 2025 am 11:04 AM

建物のウェブサイトはプログラミングです。 HTMLとCSSの作成はプログラミングです。私はプログラマーです。ここでCSS-Tricksを読んでいる場合、あなたは'

サイトから未使用のCSSをどのように削除しますか?サイトから未使用のCSSをどのように削除しますか?Apr 14, 2025 am 10:59 AM

ここに'私が前もって知るのが好きなこと:これは難しい問題です。あなたがここに上陸した場合、あなたはあなたが伝えることができるツールを指し示すことを望んでいるので、あなたが'

ピクチャーインピクチャーWeb APIの紹介ピクチャーインピクチャーWeb APIの紹介Apr 14, 2025 am 10:57 AM

Picture-in-Pictureは、2016年にMacos SierraをリリースしたSafariブラウザでWebに初めて登場しました。ユーザーがポップできるようになりました。

ギャツビーを使用してぼやけた効果のために画像を整理して準備する方法ギャツビーを使用してぼやけた効果のために画像を整理して準備する方法Apr 14, 2025 am 10:56 AM

Gatsbyは、画像の処理と処理の素晴らしい仕事をしています。たとえば、手動で画像の最適化で時間を節約するのに役立ちます

ああ、パディングの割合は親要素の幅に基づいていますああ、パディングの割合は親要素の幅に基づいていますApr 14, 2025 am 10:55 AM

私は今日、私の頭の中で完全に間違っていたことをパーセンテージベース(%)のパディングについて学びました!パディングの割合はに基づいているといつも思っていました

See all articles

ホット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ヘンタイを無料で生成します。

ホットツール

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

PhpStorm Mac バージョン

PhpStorm Mac バージョン

最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

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