fetch实践 替代jquery封装的ajax

来源:互联网 发布:皖南医学院校园网络 编辑:程序博客网 时间:2024/06/03 20:26

 看到了一些有关于fetch的文章,随着ES6规范的落实,JS原生API越来越健全,所以打算试试fetch来取代ajax。

以下为前端部分,做了注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fetch("http://127.0.0.1:3000/users/test",//fetchurl
{
method:"POST",//fetchpostget
headers:{"Content-Type":"application/x-www-form-urlencoded"},//body
body:"firstName=Nikhil&favColor=blue&password=easytoguess"//
})
.then(function(res){
if(res.ok){//OK
returnres.json();//json便alertres.json
    ()then
}elseif(res.status==401){
alert("Oops!Youarenotauthorized.");
}
},
function(e){//
alert("Errorsubmittingform!");
})
.then(function(text){
console.log('gottext',text)//json
});

 

 

Body共有五个属性

arrayBuffer()
blob()
json()
text()
formData()

 

以nodejs搭建后台,用的是express框架,以下为后台接口代码

 

router.post('/test', function(req, res, next) {
console.log(req.body);//在控制台输出接受到的内容
res.setHeader("Access-Control-Allow-Origin", "*");//接受所有跨域请求
res.set('Content-Type','text/plain');
res.send({//json格式传回数据
'first':'aa','he':'bb'
});
});

 

点击最上面的黑线,就可以在Console里找到我们发回的数据。

 

1 0
原创粉丝点击