版权声明:本文为博主原创文章,未经博主允许不得转载。除非支付宝搜索 7212127 领个红包再转载。 https://blog.csdn.net/twodogya/article/details/84840599
之前写过一篇《ajax、axios、fetch之间的详细区别以及优缺点》 戳这里
1.封装 (http.js)
class Ajax {
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'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => resolve('数据删除成功!'))
.catch(err => reject(err))
})
}
}
export default new Ajax();//ES6导出
2.调用
import http from "./http.js"//引入方式 这里用的是ES6的方法,需要babel配合webpack打包
//普通引入使用src引入之后 const http = new Ajax(); 即可
// get请求数据
http.get('http://jsonplaceholder.typicode.com/users')
.then((data) => {
console.log(data)
})
.catch(err => console.log(err))
// post传输数据
const data = {
name: 'candy',
username: 'candy',
email: '[email protected]'
};
//post user
http.post('http://jsonplaceholder.typicode.com/users', data)
.then(data => console.log(data))
.catch(err => console.log(err))
// update user ,修改后会发现修改后ID为2的数据会变成上页面定义的data
http.put('http://jsonplaceholder.typicode.com/users/2', data)
.then(data => console.log(data))
.catch(err => console.log(err))
//delete user 删除下标为2里的数据
http.delete('http://jsonplaceholder.typicode.com/users/2', data)
.then(data => console.log(data))
.catch(err => console.log(err))
贴个征婚启事~~~
受朋友之托。
女,程序员,22岁,未婚,身高167cm,体重48KG,山东青岛。
目前在阿里巴巴工作,负责支付宝相关业务,工号 7212127 支付宝搜索工号可见照片和个人信息呢。
漂亮大方,爱好读书、健身、游泳、吃鸡。
青岛有房一套,有车。
父母退休,家庭不拜金、人务实,一直没有合适的男朋友。
她本人要求不高,只要对她真心好就行。