使用Promise封裝fetch庫(增刪改查)

大壯在七月發表於2020-10-05
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script type="text/javascript">
		// 使用Promise封裝fetch庫(增刪改查)
			class EasyHttp{
				// 封裝get 請求
				get(url){
					return new Promise((resolve, reject) => {
						fetch(url)
							.then(res => res.json())
							.then(data => resolve(data))
							.catch(err => reject(err))
					})
				}
				// 封裝 post 請求
				post(url, data){
					return new Promise((resolve, reject) => {
						fetch(url, {
							method:"POST",
							headers:{
								'Content-type': 'application/json'
							},
							body:JSON.stringify(data)
						})
					
					.then(res => res.json())
					.then(data => resolve(data))
					.catch(err => reject(err))
				})
				}


				// 封裝 put 請求
				put(url, data){
					return new Promise((resolve, reject) => {
						fetch(url, {
							method:"PUT",
							headers:{
								'Content-type': 'application/json'
							},
							body:JSON.stringify(data)
						})
					
					.then(res => res.json())
					.then(data => resolve(data))
					.catch(err => reject(err))
				})
				}

				// 封裝 delete 請求
				delete(url, data){
					return new Promise((resolve, reject) => {
						fetch(url, {
							method:"DELETE",
							headers:{
								'Content-type': 'application/json'
							}
						})
					
					.then(res => res.json())
					.then(data => resolve('資料刪除成功!'))
					.catch(err => reject(err))
				})
				}
			}

			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>

相關文章