fetch的基本用法

fetch的基本用法

fetch("/abc").then(data=>{
    // text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,用于获取和后台返回的数据
    return data.text();
}).then(ret=>{
    // 注意这里得到的才是最终的数据
    console.log(ret);
})

基本的 get 请求

第一种写法

后台路由

app.get("/books", (req, res) => {
    res.send("传统的URL传递参数!" + req.query.id);
})

fetch 请求

默认为 get 请求(第二个参数),所以就不写了

fetch("http://127.0.0.1:3000/books?123").then(function(data){
    return data.text();
}).then(function(data){
    console.log(data);
});

第二种写法

后台路由

app.get("/books/:id", (req, res) => {
    res.send("Restful的URL传递参数!" + req.params.id);
})

fetch 请求

默认为 get 请求(第二个参数),所以就不写了

fetch("http://127.0.0.1:3000/books/123").then(function(data){
    return data.text();
}).then(function(data){
    console.log(data);
});

delete 请求和 get 请求基本类似

基本的 post 请求

第一种用法

后台路由

app.post("books", (req, res) => {
    res.send("POST的URL传递参数!" + req.body.uname + "---" + req.body.pwd);
})

fetch 请求

fetch("http://127.0.0.1:3000/books", {
    method: "post",
    body: "uname=lisi&pwd=123",
    header: {
        "Content-Type": "application/x-www-form-urlencoded"
    }
}).then(function(data){
    return data.text();
}).then(function(data){
    console.log(data)
})

第二种用法

后台路由

app.post("books", (req, res) => {
    res.send("POST的URL传递参数!" + req.body.uname + "---" + req.body.pwd);
})

fetch 请求

fetch("http://127.0.0.1:3000/books", {
    method: "post",
    body: JSON.stringify({
        uname: "张三",
        pwd: "456"
    }),
    header: {
        "Content-Type": "application/json"
    }
}).then(function(data){
    return data.text();
}).then(function(data){
    console.log(data)
})

put 请求和 post 请求基本类似

fetch 响应结果

  • text(): 将返回体处理成字符串类型
  • json(): 返回结果和 JSON.parse(responseText) 一样

后台接口

app.get("/json", (req, res) => {
    res.json({
        uname: "lisi",
        age: 13,
        gender: "male"
    });
})

fetch 请求

第一种(推荐)

fetch("http://127.0.0.1:3000/books").then(function(data){
    return data.json();
}).then(function(data){
    console.log(data)
})

第二种

fetch("http://127.0.0.1:3000/books").then(function(data){
    return data.text();
}).then(function(data){
    var obj = JSON.parse(data);
    console.log(obj.uname, obj.age, obj.gender);
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码小余の博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值