fetch的基本用法
步骤:
- //替代
Ajax获取数据fetch()的参数URLfecth也有.then()方法- 在
.then()中的参数方法中,调用text()text()返回的是一个Promise对象- 再用
.then()才可以获取数据
fetch('http://localhost:3000/data').then(data=>{
return data.text();//调用text的是参数方法的参数data
}).then(ret=>{
console.log(ret);//这才是获取的数据
})
fetch发送请求参数给后端
通过
GET传参
fetch()第二个参数是一个对象,里面是method,{method:'get'}- 通过在
fetch()第一个参数的url传,直接加'/xxx'- 后台服务器获取这个参数需要在
get中的url加上'/:id'用req.params.id来接收
fetch('http://localhost:3000/data/123',
{method:'get'}).then(data=>{
return data.text();
}).then(ret=>{
console.log(ret);
})
后台服务器(不太懂)
app.get('/data/:id',(req,res)=>{
res.send('get传参'+req.params.id);
})
通过
DELETE传参大致步骤和
get差不多,将js和后端服务器的get改成delete即可
通过
POST传参
- 不需要在
url中传参fetch()的第二个参数是一个对象,其中不止有method了,还需要加body和headers属性第一种方法,传统点的
body用字符串表示多个参数body:'uname=张三&pwd=123'headers是一个对象,只有一个'Content-Type'属性且值是唯一的'application/x-www-form-urlencoded'- 总体就是
fetch('http://localhost:3000/data',
{
method:'post',
body:'uname=张三&pwd=123',
headers:{
'Content-Type':'application/x-www-form-urlencode'
}
})
- 后台获取参数需要用
body中获取,且需要用到中间件body-parser
const bodyParser = require('body-parser');
app.post('/data', (req, res) => {
res.send('post传参' + req.body.uname + '---' + req.body.pwd);
})
第二种方法,用
json
body变成一个JSON.stringify方法,参数是一个对象,属性为各键值对即要传的参数headers的Content-Type改成'application/json'
fetch('http://localhost:3000/data',
{
method: 'get',
body: JSON.stringify({
uname:李四,
pwd:123,
}),
headers: {
'Content-Type': 'application/json'
}
})
- 后台需要让后台使用中间件支持
json
const bodyParser = require('body-parser');
app.use(bodyParser.json());
通过
PUT传参
fetch()与POST大致一样,需要将method改成PUT- 但因为
PUT是修改数据,在URL应该加/123,加上id
fetch的json()方法使用
- 之前基本用法已经使用过
text()方法,text()方法返回是字符串类型json()方法的使用
- 同基本用法里一样,将
text()改为json()即可- 返回的是一个
json对象,可调用里面的属性
fetch('http://localhost:8000'/json).then(function (data) {
return data.json();//这里json
}).then(function (ret) {
console.log(ret.uname+ret.age);
})
- 若是用
text()获取的json数据,返回的是一个字符串s,可以通过JSON.parse(s)来得到对象