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 サイトの他の関連記事を参照してください。

raceslimitationsinclude:1)asteeplearningcurveduetoitsvastecosystem、2)seochallengeswithsclient-siderEndering、3)潜在的なパフォーマンスのinlargeapplications、4)complenstatemanagementasappsgrow、and5)suneedtokeepupwithovolution

ReactisChallengingを使用して、SteepLearNdParadigMshiftOconpontenAchitecture.1)startisofficialdocumentation forasolidfoundation.2)relondingjsxandjavascriptwithinit.3)LearntousefunctionalcompotontiTateを理解してください

coreChallengeingEneratingは、duniqueys consinistinsidentifientiversre-renderseforeffiencedomupdates.1)aseenaturalKeysisisisisisisisedisederiableiableiaibuniqueandStable.2)denatekeysBaseTheBasedOnMultipreattributive.2)を無効にすることを非難することを解決します

javascriptfatigueinReactismainageable with rikeislikedivedingingindininginginformationscors.1)whatyouneedwhenyouneedit、focusingonprojectrelevance.2)

ESTESTROACTCOMPONENTSINGTHESESTATEHOOK、USEJESTANDREACTINTINGLIBRARYTOSIMULATE INTERACTIONSIONDANDVERIFYISTAMESISINTHEUI.1)RENDERTHECONCENTANDCHECKECHINITATA.2)SimulateUserIractionSionsionsionsionsionsionslikeClickSorformSubmissions.3)

keysinReactarecialforptimizingperformancebyididingineffictientListupdates.1)usekeystoidentifideidifyandtracklistelements.2)ArrayIndicesassyStopreventPerformanceSues.3)suoseStableidedifierslikeItem.idtomaincomentaindtateandiproveperift

ReactKeySareUniqueIdentifiersiersiderSuredStrovereconconiniationEfficiency.1)theyctrackChangesinListitems、2)sultanduniqueidentifiersiirsiTeemidssisssississmendを使用して、3)ArrayIndicesAssayStopReventisSuseSUSEORINGを回避します

sinqueysarecrucialinReactforoptimizing andMaintainingcomponentStateIntegrity.1)useanaturaluniqueidentifierfromyourdataifaibable.2)ifnonaturalidentifierexists、発電済みのKeyusingingingingalibrarylikuuid.3)


ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

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

人気の記事

ホットツール

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

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

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

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

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。
