ReactJS에서 Axios를 사용하는 방법 - GET 및 POST 요청

Susan Sarandon
풀어 주다: 2024-10-15 12:24:01
원래의
994명이 탐색했습니다.

Cara Penggunaan Axios di ReactJS - GET dan POST Request

ReactJS에서 Axios를 사용하는 방법

소개

Axios는 GET, POST, PUT, DELETE 등과 같은 HTTP 요청을 수행하는 데 널리 사용되는 라이브러리입니다. Axios는 쉬운 구문을 제공하고 Promise를 지원하므로 React 애플리케이션에 사용하기에 매우 적합합니다. 이 글에서는 ReactJS 애플리케이션에서 Axios를 사용하는 방법에 대해 설명합니다.

Axios 설치
React 프로젝트에 Axios가 설치되어 있는지 확인하세요.

npm install axios
로그인 후 복사

React 컴포넌트에서 Axios 사용
예를 들어, GET 메서드를 사용하여 API에서 데이터를 검색하고 이를 React 구성 요소에 표시하려고 합니다.

  1. 요청 받기:
import React, { useEffect, useState } from 'react';
import axios from 'axios';

const App = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
        setData(response.data);
        setLoading(false);
      } catch (error) {
        setError(error);
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {data.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
};

export default App;

로그인 후 복사

설명:

  • 구성요소가 처음 로드될 때 useEffect를 사용하여 fetchData 함수를 호출합니다.
    • axios.get은 API URL에서 데이터를 검색하는 데 사용됩니다.
    • 상태 데이터, 로드 및 오류는 검색된 데이터, 로드 상태 및 오류를 저장하는 데 사용됩니다.

  1. POST 요청: 서버에 데이터를 보내려면 다음과 같이 POST 메서드를 사용할 수 있습니다.
import React, { useState } from 'react';
import axios from 'axios';

const App = () => {
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
        title,
        body,
      });
      console.log('Response:', response.data);
      alert('Post successfully created!');
    } catch (error) {
      console.error('Error posting data:', error);
    }
  };

  return (
    <div>
      <h1>Create a Post</h1>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          placeholder="Title"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
        />
        <textarea
          placeholder="Body"
          value={body}
          onChange={(e) => setBody(e.target.value)}
        ></textarea>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default App;

로그인 후 복사

설명:

  • axios.post 메소드는 제목과 본문 데이터를 API로 보내는 데 사용됩니다.
  • handleSubmit 함수는 양식 제출을 처리하고 데이터를 서버로 보냅니다.

위 내용은 ReactJS에서 Axios를 사용하는 방법 - GET 및 POST 요청의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!