▼비동기통신 Axios 사용방법 (GET, POST, DELETE, FETCH)▼
[리액트 심화] 비동기통신 Axios 사용방법 (GET, POST, DELETE, FETCH)
1. GET: 데이터 조회 import { useEffect, useState } from 'react'; import './App.css'; import axios from 'axios'; function App() { const [todos, setTodos] = useState(null); const [inputValue, setInpuValue] = useState({ //id : json의 방식의 데이터
zerotonine2da.tistory.com
1. Axios란?
- Promise 기반 HTTP 통신 가능한 라이브러리
1-1 Fetch와 차이점
- 자바스크립트 내장 라이브러리 (설치 x)
- 단점
(1) 지원하지 않는 브라우저가 존재
(2) 개발자에게 불친절한 response
(3) axios에 비해 부족한 기능
=> Axios를 사용하겠음!
2. VS code 터미널 실행
(1) axios 추가
yarn add axios
(2) json-server 추가
yarn add json-server
(3) src폴더 - db.json 파일 추가
(4) 리액트 : localhost3000 / DB : localhost4000 (서버와 클라이언트가 다른 공간에 있다고 생각하기)
yarn json-server --watch db.json --port 4000
3. 메서드 (client -> server)
▶ path 방법으로 접근 가능
▶ 더 디테일한 내용은 쿼리스트링으로 접근 가능
4. VS code : GET / axios.get('~~~') 사용
[App.jsx]
▶ axios.get('~~~') 으로 db.json의 데이터를 가져올 수 있음
▶ 가져온 데이터는 useState를 사용해서 상태값 변경을 해줌
▶ map함수를 이용해서 데이터 가져오기 ( 오류는 옵셔널체이닝으로 해결 가능)
리액트 오류 : Uncaught TypeError: Cannot read properties of null (reading 'map') / 옵셔널체이닝으로 해결 가능
[App.jsx] import { useEffect, useState } from 'react'; import './App.css'; import axios from 'axios'; function App() { const [todos, setTodos] = useState(null); const fetchTodos = async () => { const { data } = await axios.get('http://localhost:4002/todos'
zerotonine2da.tistory.com
[db.json]
끝.
[출처]
https://www.npmjs.com/package/json-server?activeTab=readme
json-server
Get a full fake REST API with zero coding in less than 30 seconds. Latest version: 0.17.4, last published: 2 months ago. Start using json-server in your project by running `npm i json-server`. There are 330 other projects in the npm registry using json-ser
www.npmjs.com
'React' 카테고리의 다른 글
[리액트 심화] 비동기통신 Axios interceptor (0) | 2023.11.28 |
---|---|
리액트 오류 : A component is changing a controlled input to be uncontrolled. (0) | 2023.11.28 |
리액트 오류 : Uncaught TypeError: Cannot read properties of null (reading 'map') / 옵셔널체이닝으로 해결 가능 (1) | 2023.11.28 |
[리액트 심화] HTTP 통신 / URL 구성 (1) | 2023.11.28 |
[리액트 심화] json-server 사용 방법 (+ 특정 포트 지정) (0) | 2023.11.28 |