πŸ‘¨‍πŸ’» kimtongting
article thumbnail

 

 

react hooks - axios

 

axios λͺ¨λ“ˆν™”

axiosλŠ” ν†΅μ‹ μœΌλ‘œ ν•œ κ³³μ—μ„œλ§Œ μ“°μ΄λŠ” 것이 μ•„λ‹ˆκΈ° λ•Œλ¬Έμ—, μœ μ§€λ³΄μˆ˜ 및 가독성을 μœ„ν•΄ λͺ¨λ“ˆν™”κ°€ ν•„μš”ν•©λ‹ˆλ‹€.

이전 κΈ€μ—μ„œ μž‘μ„±ν•œ ν”„λ‘œμ νŠΈ 디렉토리 ꡬ성에 따라,

'utils' 디렉토리에 api.js λΌλŠ” react.js λ₯Ό μƒμ„±ν•΄μ„œ μ—¬λŸ¬ νŽ˜μ΄μ§€μ—μ„œ ν™œμš©ν•˜μ˜€μŠ΅λ‹ˆλ‹€.

 

api.js μ„ μ–Έ

import axios from 'axios';

const API =axios.create({
    //baseURL: `http://localhost:8080/common`,
    timeout: 30000,
    headers: {
        "Content-Type" : `application/json;charset=UTF-8`,
        "Access-Control-Allow-Origin": "*",
        "Accept": "application/json",
    }
});
export default API;

 

ν”„λ‘œμ νŠΈ λ‚΄ μ‚¬μš©λ°©λ²•

//api μ„ μ–Έ
import API from 'utils/api';

//onClick μ—μ„œ μ‚¬μš©λ°©λ²•

<form action="#" name="loginFrm" method="post" onSubmit={handleSubmit}>
	<button type="submit">둜그인</button>
</form>

    const handleSubmit= (e)=>{
        e.preventDefault();
        async function callAPI(){
            const res = await API.post("/login", params)
            console.log(res.data)
        }
        callAPI();
    };
    
//νŽ˜μ΄μ§€ 호좜 μ‹œ μ‚¬μš©λ°©λ²• useEffect
    useEffect(() => {        
        async function callAPI(){
            const res = await API.post("/list", params)
            console.log(res.data)            
        }
        callAPI();
    }, []);

 

 

 

 

λ°˜μ‘ν˜•
profile

πŸ‘¨‍πŸ’» kimtongting

@kimtongting μž…λ‹ˆλ‹€

ν¬μŠ€νŒ…μ΄ μ’‹μ•˜λ‹€λ©΄ "μ’‹μ•„μš”β€οΈ" λ˜λŠ” "κ΅¬λ…πŸ‘πŸ»" ν•΄μ£Όμ„Έμš”!