TS & JSON

김수민·2023년 2월 23일
0

TypeScript

목록 보기
7/8

json-server

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>
		</>
	);
};
profile
sumin0gig

0개의 댓글