Reactでaxiosリクエストを送信する方法
axios リクエストを送信するための React メソッド: 1. 「npm install axios --save」コマンドを使用して axios をインストールします; 2. typescript を使用して axios の依存関係を反応ファイルにインポートします; 3. 「axios.get」を使用しますまたは、「axios(config { ... })」を使用して GET リクエストを作成します。
このチュートリアルの動作環境: Windows 10 システム、react18.0.0 バージョン、Dell G3 コンピューター。
react で axios リクエストを送信するにはどうすればよいですか?
axios を使用して React でリクエストを送信する一般的な方法
React に axios 依存関係をインストールして導入する
React プロジェクトで axios リクエストを使用するまず axios をインストールする必要があります:
npm install axios --save
次に、typescript を使用して axios の依存関係を反応ファイルにインポートします:
import axios from 'axios';
Use axios for GET request
When using GET requests axios 2 つの方法:
1 つは axios.get
もう 1 つは axios(config { ... } ) メソッドを使用する
axios.get メソッドを使用する
カプセル化された axios.get を使用してリクエストするための一般的な形式は次のとおりです:
// Make a request for a user with a given ID axios.get('/getUser?id=12345') .then(function (response) { // handle success console.log(response); // update state or do something this.setState({ // ... }) }) .catch(function (error) { // handle error console.log(error); }) .then(function () { // always executed }); // Optionally the request above could also be done as axios.get('/getUser', { params: { // 这里的参数设置为URL参数(根据URL携带参数) id: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed }); // Want to use async/await? Add the `async` keyword to your outer function/method. async function getUser() { try { const response = await axios.get('/getUser?id=12345'); console.log(response); } catch (error) { console.error(error); } }
Use axios(config {...})
Use axios(config {...}) を使用して、次の形式で GET リクエストを送信します。
axios({ method: 'get', url: '/getUser', params: { id: 12345, } }) .then(function (response) { console.log(response); });
上記の get リクエストで送信される URL は次のとおりです。
http:HOST_IP:XXXX/getUser?id=12345
POST リクエストに axios を使用する
GET リクエストと同様に、POST を使用するリクエスト メソッドが 2 つあります。
Use axios.post
axios.post('/createUser', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Use axios(config {...})
// Send a POST request axios({ method: 'post', url: '/createUser', data: { // 这里data中的参数为requestBody参数,服务端需要使用@RequestBody注解进行获取 firstName: 'Fred', lastName: 'Flintstone' } }).then(function (response) { console.log(response); }).catch(function (error) { console.log(error); });
axios(config {}) を使用して GET を実行する場合は注意が必要ですまたは、POST リクエストを送信するとき、GET リクエストのパラメータは URL パラメータであり、POST リクエストのデータは RequestBody パラメータです。@RequestBody アノテーションを受信するにはサーバーで使用する必要があり、Spring Boot は自動的に解析できます。それを対応する Java オブジェクトに組み込みます。
複数のリクエストを同時に送信する
axios を使用すると、一度に複数のリクエストを送信することもできます:
function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // Both requests are now complete }));
詳細な設定オブジェクトの設定項目
axios の Readme ドキュメントには、次のような config オブジェクトの具体的な設定手順が記載されています。
{ // `url` is the server URL that will be used for the request url: '/user', // `method` is the request method to be used when making the request method: '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: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, // FormData or Stream // You may modify the headers object. transformRequest: [function (data, headers) { // Do whatever you want to transform the data return data; }], // `transformResponse` allows changes to the response data to be made before // it is passed to then/catch transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers` are custom headers to be sent headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request // Must be a plain object or a URLSearchParams object params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function (params) { return Qs.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 of one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer data: { firstName: 'Fred' }, // syntax alternative to send data into the body // method post // only the value is sent, not the key data: 'Country=Brasil&City=Belo Horizonte', // `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, // default is `0` (no timeout) // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier. // Return a promise and supply a valid response (see lib/adapters/README.md). adapter: function (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`. // Please note that only HTTP Basic auth is configurable through this parameter. // For Bearer tokens and such, use `Authorization` custom headers instead. auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` indicates the type of data that the server will respond with // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' // browser only: 'blob' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` allows handling of progress events for uploads // browser only onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` allows handling of progress events for downloads // browser only onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength` defines the max size of the http response content in bytes allowed maxContentLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` // or `undefined`), the promise will be resolved; otherwise, the promise will be // rejected. validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` defines the maximum number of redirects to follow in node.js. // If set to 0, no redirects will be followed. maxRedirects: 5, // default // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http // and https requests, respectively, in node.js. This allows options to be added like // `keepAlive` that are not enabled by default. httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // `proxy` defines the hostname and port of the proxy server. // You can also define your proxy using the conventional `http_proxy` and // `https_proxy` environment variables. If you are using environment variables // for your proxy configuration, you can also define a `no_proxy` environment // variable as a comma-separated list of domains that should not be proxied. // Use `false` to disable proxies, ignoring environment variables. // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and // supplies credentials. // This will set an `Proxy-Authorization` header, overwriting any existing // `Proxy-Authorization` custom headers you have set using `headers`. proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` specifies a cancel token that can be used to cancel the request // (see Cancellation section below for details) cancelToken: new CancelToken(function (cancel) { }) }
axios の戻り値オブジェクトの応答
axios が作成した後に取得される応答オブジェクトの形式リクエストは次のとおりです:
{ // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the HTTP headers that the server responded with // All header names are lower cased and can be accessed using the bracket notation. // Example: `response.headers['content-type']` headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {} }
リクエストの後に then メソッドを使用すると、応答オブジェクトの各属性値を取得できます。データはサーバーから返された対応するオブジェクトです:
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 のグローバル設定
axios を使用する場合、次の設定のように、axios オブジェクトのグローバル設定を行うことができます。この設定は、axios が配置されている現在の JavaScript クラス内のすべての axios リクエストに適用されます。
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';
axios の単一インスタンス化設定
axios をグローバルに設定する必要がない場合は、次のように axios オブジェクトを使用するときに単一のオブジェクトを設定できます。
##axios インターセプターの使用axios インターセプターを使用してリクエストをインターセプトし、リクエストの送信前またはレスポンス (メソッド) に応答する前にカスタマイズした設定を行うことができます。
// Set config defaults when creating the instance const instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
When インターセプターを削除する必要がある場合は、次の手順を実行します:
// Add a request interceptor axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error return Promise.reject(error); });
定義されたインターセプターをカスタム axios インスタンスに追加することもできます:
const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor);
上記の情報の一部は axios ドキュメントから参照されています。詳細については、https://github.com/axios/axios
を参照してください。推奨される学習: 「
react ビデオ チュートリアル##」 #"以上がReactでaxiosリクエストを送信する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

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

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

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

ホットトピック











React と RabbitMQ を使用して信頼性の高いメッセージング アプリケーションを構築する方法 はじめに: 最新のアプリケーションは、リアルタイム更新やデータ同期などの機能を実現するために、信頼性の高いメッセージングをサポートする必要があります。 React はユーザー インターフェイスを構築するための人気のある JavaScript ライブラリであり、RabbitMQ は信頼性の高いメッセージング ミドルウェアです。この記事では、React と RabbitMQ を組み合わせて信頼性の高いメッセージング アプリケーションを構築する方法を紹介し、具体的なコード例を示します。 RabbitMQ の概要:

ReactRouter ユーザーガイド: フロントエンドルーティング制御の実装方法 シングルページアプリケーションの人気に伴い、フロントエンドルーティングは無視できない重要な部分になりました。 React エコシステムで最も人気のあるルーティング ライブラリとして、ReactRouter は豊富な機能と使いやすい API を提供し、フロントエンド ルーティングの実装を非常にシンプルかつ柔軟にします。この記事では、ReactRouter の使用方法と具体的なコード例を紹介します。 ReactRouter を最初にインストールするには、次のものが必要です

PHP、Vue、React: 最適なフロントエンド フレームワークを選択するには?インターネット技術の継続的な発展に伴い、フロントエンド フレームワークは Web 開発において重要な役割を果たしています。 PHP、Vue、React は 3 つの代表的なフロントエンド フレームワークであり、それぞれに独自の特徴と利点があります。使用するフロントエンド フレームワークを選択するとき、開発者はプロジェクトのニーズ、チームのスキル、個人の好みに基づいて情報に基づいた決定を下す必要があります。この記事では、PHP、Vue、React の 3 つのフロントエンド フレームワークの特徴と用途を比較します。

Java フレームワークと React フレームワークの統合: 手順: バックエンド Java フレームワークをセットアップします。プロジェクト構造を作成します。ビルドツールを設定します。 React アプリケーションを作成します。 REST API エンドポイントを作成します。通信メカニズムを構成します。実際のケース (SpringBoot+React): Java コード: RESTfulAPI コントローラーを定義します。 React コード: API によって返されたデータを取得して表示します。

React を使用して応答性の高いバックエンド管理システムを開発する方法 インターネットの急速な発展に伴い、日々の業務を処理するために効率的で柔軟で管理が容易なバックエンド管理システムを必要とする企業や組織が増えています。現在最も人気のある JavaScript ライブラリの 1 つである React は、ユーザー インターフェイスを構築するための簡潔で効率的かつ保守しやすい方法を提供します。この記事では、React を使用して応答性の高いバックエンド管理システムを開発する方法と、具体的なコード例を紹介します。まず React プロジェクトを作成します

VUE.JSは、中小規模のプロジェクトや迅速な反復に適していますが、Reactは大規模で複雑なアプリケーションに適しています。 1)Vue.jsは使いやすく、チームが不十分な状況やプロジェクトスケールが小さい状況に適しています。 2)Reactにはより豊富なエコシステムがあり、高性能で複雑な機能的ニーズを持つプロジェクトに適しています。

ReactはJSXとHTMLを組み合わせてユーザーエクスペリエンスを向上させます。 1)JSXはHTMLを埋め込み、開発をより直感的にします。 2)仮想DOMメカニズムは、パフォーマンスを最適化し、DOM操作を削減します。 3)保守性を向上させるコンポーネントベースの管理UI。 4)国家管理とイベント処理は、インタラクティブ性を高めます。

React には、イベント処理関数、useEffect や useCallback、上位コンポーネントなどのクロージャがあります。詳細な紹介: 1. イベント処理関数のクロージャ: React では、コンポーネント内でイベント処理関数を定義すると、関数はクロージャを形成し、コンポーネントのスコープ内のステータスとプロパティにアクセスできます。このようにして、コンポーネントの状態とプロパティをイベント処理関数で使用して対話型ロジックを実装できます; 2. useEffect や useCallback のクロージャなど。
