ES7 async封裝fetch庫(增刪改查)

2020-10-06 12:00:59
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script type="text/javascript">
		// 使用Promise封裝fetch庫(增刪改查)
			class EasyHttp{
				// 封裝get 請求
				async get(url){
                    const response = await fetch(url)
                    const resData = await response.json() 
                    return resData
				}
				// 封裝 post 請求
				async post(url, data){

                    const response = await fetch(url, {
							method:"POST",
							headers:{
								'Content-type': 'application/json'
							},
							body:JSON.stringify(data)
						})
                    const resData = await response.json()
                    return resData

				}


				// 封裝 put 請求
				async put(url, data){
					const response = await fetch(url, {
							method:"PUT",
							headers:{
								'Content-type': 'application/json'
							},
							body:JSON.stringify(data)
						})
					const resData = await response.json()
                    return resData
				}

				// 封裝 delete 請求
				async delete(url, data){
					const response = fetch(url, {
							method:"DELETE",
							headers:{
								'Content-type': 'application/json'
							}
						})
					const resData = await "資料刪除成功"
                    return resData
				}
			}

			const http = new EasyHttp;

			// get請求資料

			http.get('http://jsonplaceholder.typicode.com/users')
				.then((data) => {
					console.log(data)
				})
				.catch(err => console.log(err))

			//post

			const data = {
				name:"xiangming",
				username:"小明",
				email:"1231231@qq.com"
			}
			http.post('http://jsonplaceholder.typicode.com/users',data)
				.then((data) => console.log(data))
				.catch(err => console.log(err))

			//put
			http.put('http://jsonplaceholder.typicode.com/users/2',data)
				.then((data) => console.log(data))
				.catch(err => console.log(err))

			//delete
			http.delete('http://jsonplaceholder.typicode.com/users/2')
				.then((data) => console.log(data))
				.catch(err => console.log(err))

		</script>
	</head>
	<body>
		
	</body>
</html>