fetch概述
- 基本特性
- 更加简单的数据获取方式,功能更强大,更灵活,可以看做是xhr的升级版
- 基于Promise实现
- 语法结构
fetch(url).then(fn2)
.then(fn3)
...
.catch(fn)
fetch的基本用法
fetch('/abc').then(data=>{
//text()方法属于fetchAPI的一部分,返回一个Promise实例对象,用于获取后台返回的数据
return data.text();
}).then(ret=>{
//注意这里得到的才是最终的数据
console.log(ret);
});
fetch请求参数
常用配置选项
* method(String):HTTP请求方法,默认为GET(GET,POST,PUT,DELETE)
* body(String):Http的请求参数
* headers(Object):HTTP的请求头,默认为{}
fetch('/abc',{
method:'get'
}).then(data=>{
return data.text();
}).then(ret=>{
//注意这里得到的才是最终的数据
console.log(ret);
});
GET请求方式的参数传递
- 传统形式:
fetch('/books?id=123').then(data=>{
return data.text();
}).then(ret=>{
//注意这里得到的才是最终的数据
console.log(ret);
});
//后台接收
app.get('/books', (req, res) => {
res.send('传统:' + req.query.id);
});
- Restfult形式:
fetch('/books/123',{
method:'get'
}).then(data=>{
return data.text();
}).then(ret=>{
//注意这里得到的才是最终的数据
console.log(ret);
});
//后台接收
app.get('/books/:id', (req, res) => {
res.send('restful:' + req.params.id);
});
DELETE请求方式的参数传递
- 与get传参方式一样,将get改为delete
POST请求方式的参数传递
fetch('http://localhost:3000/books',{
method:'post',
body:'uname=tkrj&pwd=123',
headers:{
'Content-Type':'application/x-www-form-urlencoded',
}
}).then(data => {
return data.text();
}).then(ret => {
//注意这里得到的才是最终的数据
console.log(ret);
});
//后台接收
app.post('/books', (req, res) => {
res.send('post:' + req.body.uname+'---'+req.body.pwd);
});
JSON格式
fetch('http://localhost:3000/books',{
method:'post',
body:JSON.stringify({
uname:'list',
pwd:123
}),
headers:{
'Content-Type':'application/json',
}
}).then(data => {
return data.text();
}).then(ret => {
//注意这里得到的才是最终的数据
console.log(ret);
});
PUT请求方式的参数传递
fetch('http://localhost:3000/books/123',{
method:'put',
body:JSON.stringify({
uname:'list',
pwd:789
}),
headers:{
'Content-Type':'application/json',
}
}).then(data => {
return data.text();
}).then(ret => {
//注意这里得到的才是最终的数据
console.log(ret);
});
// 后台接收
app.put('/books/:id', (req, res) => {
res.send('put:' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd);
});
fetch响应结果
- text():将返回体处理成字符串类型
- json():返回结果和JSON.parse(responseText)一样
json()
fetch('http://localhost:3000/json').then(data => {
return data.json();
}).then(ret => {
//得到返回的对象
console.log(ret);
//改为text()则得到的是字符串,需要转换为对象
//var obj = JSON.parse(data);
});
//后台直接返回一个对象
app.get('/json', (req, res) => {
res.json({
uname: 'tkrj',
age:13
});
});