fetch的用法

5,048 阅读2分钟

fetch的基本用法

步骤:

  • //替代Ajax获取数据
  • fetch()的参数URL
  • fecth也有.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了,还需要加bodyheaders属性

第一种方法,传统点的

  • 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方法,参数是一个对象,属性为各键值对即要传的参数
  • headersContent-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)来得到对象