반응으로 Axios 요청을 보내는 방법
반응에서 axios 요청을 보내는 방법: 1. "npm install axios --save" 명령을 통해 axios를 설치합니다. 2. typescript를 사용하여 반응 파일에서 axios 종속성을 가져옵니다. (config { ... })" 메소드를 사용하여 GET 요청을 수행합니다.
이 튜토리얼의 운영 환경: 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. '/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가 위치한 현재 자바스크립트 클래스의 모든 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 객체를 사용할 때 단일 객체를 설정하면 됩니다.
// 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;
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 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
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

React 및 RabbitMQ를 사용하여 안정적인 메시징 애플리케이션을 구축하는 방법 소개: 최신 애플리케이션은 실시간 업데이트 및 데이터 동기화와 같은 기능을 달성하기 위해 안정적인 메시징을 지원해야 합니다. React는 사용자 인터페이스 구축을 위한 인기 있는 JavaScript 라이브러리인 반면 RabbitMQ는 안정적인 메시징 미들웨어입니다. 이 기사에서는 React와 RabbitMQ를 결합하여 안정적인 메시징 애플리케이션을 구축하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. RabbitMQ 개요:

ReactRouter 사용자 가이드: 프런트엔드 라우팅 제어 구현 방법 단일 페이지 애플리케이션의 인기로 인해 프런트엔드 라우팅은 무시할 수 없는 중요한 부분이 되었습니다. React 생태계에서 가장 널리 사용되는 라우팅 라이브러리인 ReactRouter는 풍부한 기능과 사용하기 쉬운 API를 제공하여 프런트 엔드 라우팅 구현을 매우 간단하고 유연하게 만듭니다. 이 기사에서는 ReactRouter를 사용하는 방법을 소개하고 몇 가지 구체적인 코드 예제를 제공합니다. ReactRouter를 먼저 설치하려면 다음이 필요합니다.

PHP, Vue 및 React: 가장 적합한 프런트엔드 프레임워크를 선택하는 방법은 무엇입니까? 인터넷 기술이 지속적으로 발전함에 따라 프런트엔드 프레임워크는 웹 개발에서 중요한 역할을 합니다. PHP, Vue, React는 세 가지 대표적인 프론트엔드 프레임워크로 각각 고유한 특성과 장점을 가지고 있습니다. 사용할 프런트 엔드 프레임워크를 선택할 때 개발자는 프로젝트 요구 사항, 팀 기술 및 개인 선호도를 기반으로 정보를 바탕으로 결정을 내려야 합니다. 이 글에서는 세 가지 프론트엔드 프레임워크인 PHP, Vue, React의 특징과 용도를 비교해보겠습니다.

Java 프레임워크와 React 프레임워크의 통합: 단계: 백엔드 Java 프레임워크를 설정합니다. 프로젝트 구조를 만듭니다. 빌드 도구를 구성합니다. React 애플리케이션을 만듭니다. REST API 엔드포인트를 작성합니다. 통신 메커니즘을 구성합니다. 실제 사례(SpringBoot+React): Java 코드: RESTfulAPI 컨트롤러를 정의합니다. React 코드: API에서 반환된 데이터를 가져오고 표시합니다.

React를 사용하여 반응형 백엔드 관리 시스템을 개발하는 방법 인터넷의 급속한 발전으로 인해 점점 더 많은 회사와 조직에서 일상적인 작업을 처리하기 위해 효율적이고 유연하며 관리하기 쉬운 백엔드 관리 시스템이 필요합니다. 현재 가장 인기 있는 JavaScript 라이브러리 중 하나인 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 등의 클로저.
