찾다
웹 프론트엔드프런트엔드 Q&A반응으로 Axios 요청을 보내는 방법

반응에서 axios 요청을 보내는 방법: 1. "npm install axios --save" 명령을 통해 axios를 설치합니다. 2. typescript를 사용하여 반응 파일에서 axios 종속성을 가져옵니다. (config { ... })" 메소드를 사용하여 GET 요청을 수행합니다.

반응으로 Axios 요청을 보내는 방법

이 튜토리얼의 운영 환경: Windows 10 시스템, 반응 버전 18.0.0, Dell G3 컴퓨터.

반응으로 Axios 요청을 보내는 방법은 무엇입니까?

Axios를 사용하여 React에서 요청을 보내는 일반적인 방법

React에서 axios 종속성 설치 및 도입

React 프로젝트에서 axios 요청을 사용하려면 먼저 axios를 설치해야 합니다.

npm install axios --save

그런 다음 typescript를 사용하여 가져옵니다. 반응 파일에서 axios 종속성:

import axios from 'axios';

GET 요청에 axios 사용

axios에서 GET 요청을 사용하는 두 가지 방법이 있습니다:

  • 하나는 axios.get

  • 을 사용하는 것입니다. 다른 하나는 axios( config { ... }) method

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);
  }
}

axios(config {...} 사용 )

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를 사용하는 요청 방법도 두 가지가 있습니다.

axios.post 사용

axios.post('/createUser', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

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의 추가 정보 문서에는 구성 개체에 대한 특정 구성 지침이 있습니다.

{
  // `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. &#39;/var/run/docker.sock&#39; 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: &#39;127.0.0.1&#39;,
    port: 9000,
    auth: {
      username: &#39;mikeymike&#39;,
      password: &#39;rapunz3l&#39;
    }
  },
 
  // `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: &#39;OK&#39;,
 
  // `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[&#39;content-type&#39;]`
  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(&#39;/user/12345&#39;)
  .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가 위치한 현재 자바스크립트 클래스의 모든 axios 요청:

axios.defaults.baseURL = &#39;https://api.example.com&#39;;
axios.defaults.headers.common[&#39;Authorization&#39;] = AUTH_TOKEN;
axios.defaults.headers.post[&#39;Content-Type&#39;] = &#39;application/x-www-form-urlencoded&#39;;

axios의 단일 인스턴스 구성

axios를 전역적으로 설정할 필요가 없다면 axios 객체를 사용할 때 단일 객체를 설정하면 됩니다.

// Set config defaults when creating the instance
const instance = axios.create({
  baseURL: &#39;https://api.example.com&#39;
});
 
// Alter defaults after instance has been created
instance.defaults.headers.common[&#39;Authorization&#39;] = AUTH_TOKEN;

Axios 인터셉터 사용

을 사용할 수 있습니다. Axios 인터셉터는 요청을 보내기 전이나 응답에 응답하기 전(다음 메서드) 요청을 가로채서 사용자 정의 설정을 만드는 데 사용됩니다. 요청 및 응답 인터셉터는 다음과 같습니다.

// 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);
  });

인터셉터를 삭제해야 하는 경우 다음을 수행하세요.

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

정의된 인터셉터를 사용자 정의 Axios 인스턴스에 추가할 수도 있습니다.

const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

위 정보 중 일부는 다음에서 참조됩니다. 자세한 내용은 https://github.com/axios/axios

권장 학습: " react 비디오 튜토리얼

을 참조하세요.

위 내용은 반응으로 Axios 요청을 보내는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
React의 한계는 무엇입니까?React의 한계는 무엇입니까?May 02, 2025 am 12:26 AM

반응 말 : 1) asteeplearningcurveduetoitsvastecosystem, 2) Seochallengswithclient-siderendering, 3) PlatiperFormanceIssUseInlargeApplications, 4) ComplexStateManagementAsAppSgrow, 및 5) theneedTokeEpupWithitsHouou

React의 학습 곡선 : 새로운 개발자를위한 도전React의 학습 곡선 : 새로운 개발자를위한 도전May 02, 2025 am 12:24 AM

ReactisChallengingforbeginnersdueToitssteePlearningCurveanDParadigMshiftTocomponent 기반 Architection.1) 시작된 문서화 forasolidFoundation.2) startWithOficialDocumentationForAsolIdfoundation.2) 이해를 이해하는 방법

React에서 동적 목록을위한 안정적이고 고유 한 키 생성React에서 동적 목록을위한 안정적이고 고유 한 키 생성May 02, 2025 am 12:22 AM

thecorechallengeenderatingStableanduniquekysfordynamiclistsinconsengingconsententifiersacrossre-rendersforefficialdomupdates

JavaScript 피로 : React 및 그 도구로 최신 상태를 유지합니다JavaScript 피로 : React 및 그 도구로 최신 상태를 유지합니다May 02, 2025 am 12:19 AM

JavaScriptFatigueInreactismanageablewithstrestriveStriveStriveStiMelearningandcuratedInformationSources.1) 1))

usestate () 후크를 사용하는 테스트 구성 요소usestate () 후크를 사용하는 테스트 구성 요소May 02, 2025 am 12:13 AM

TOTESTREACTCOMPONENTSUSINSUSISTATEHOOK, useJestAndReactTestingLibraryTosimulationInteractionsandStateChangeSintheUI.1) renderTheComponentAndCheckInitialState.2) SimulateUserActionSlikeClickSorformSubMissions.3) verifyTateRecerFectsin

React의 키 : 성능 최적화 기술에 대한 깊은 다이빙React의 키 : 성능 최적화 기술에 대한 깊은 다이빙May 01, 2025 am 12:25 AM

keysinReactareCrucialforopiTizingPerformanceByIningIneficiveliceListEpdates.1) uskeyStoIndifyAndTrackListElements.2) revingArrayIndiceSkeyStopReverFormanceSues.3) 선택 가능한 식당 LikeItesteM.idtomaintaintAteAndimProvePerform

React의 열쇠는 무엇입니까?React의 열쇠는 무엇입니까?May 01, 2025 am 12:25 AM

RenderingListStoimproverCiliationeficiency를 사용하면 RECTKEYSAREUNIQUEINDIFIERSEDS (1) ISHELPREACTTRACKCHANGENLISTEMS, 2) 사용 ASSABLEANDUNICEIDERIDERSISTEMIDSISRECEMENDEND, 3) RepoySingArrayIndicesAskeyStopReventIsseswithReAdering 및 4) ENS

React에서 고유 키의 중요성 : 일반적인 함정 방지React에서 고유 키의 중요성 : 일반적인 함정 방지May 01, 2025 am 12:19 AM

고유 한 KeysAreCrucialInreactforoptoropiTizing and ComponentStateIntegrity

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 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경