json파일을 사용하여 간단한 시뮬레이션을 위한 REST API Mock server를 구축할 수 있는 틀
npm install -g json-server
json-server --watch [data.json파일 경로] --port [포트번호]
json-server --watch ./src/db/data.json --port 3003
const AddFun = () => {
const [fun,setFun]=useState(
{
name:"",
desc:""
}
);
const onChange=(e:React.ChangeEvent<HTMLInputElement> )=>{
const {name,value}= e.target;
setFun({...fun,[name]:value})
}
const submit=()=>{
fetch(`http://localhost:3003/functions`,{
method:"POST",
headers:{
"Content-Type":"application/json",
},
// 상태값 fun변수를 JSON 형태로 바꿔 body에 담았다.
body:JSON.stringify(fun)
}).then(res=>{
if(res.ok){
alert("전송 완료")
}
})
.catch(e=>console.log(e)
)
}
return (
<>
<div>
name <input name='name' onChange={onChange}/>
desc <input name='desc' onChange={onChange}/>
</div>
<button onClick={submit}>전송</button>
</>
);
};