接口调用-fetch用法

fetch概述

  1. 基本特性
    • 更加简单的数据获取方式,功能更强大,更灵活,可以看做是xhr的升级版
    • 基于Promise实现
  2. 语法结构
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
    });
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值