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);
})
fetch是现代浏览器提供的一种用于替代XMLHttpRequest(XHR)的原生JavaScript API,用于在Web应用中发起网络请求到服务器。fetch基本语法如下: ```javascript fetch(url, [options]) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` 这里的`url`是一个字符串,表示你想要从网络获取资源的地址。`options`是一个可选的参数,它是一个对象,包含了如方法(method)、头部(headers)、请求体(body)等HTTP请求的详细配置。 - `method`:请求使用的方法,如 'GET'、'POST'。 - `headers`:请求头,可以包含许多信息,如内容类型(Content-Type)。 - `body`:请求的主体内容,可以是Blob、BufferSource、FormData、URLSearchParams或USVString对象。 `fetch`函数返回一个Promise,该Promise解析为一个`Response`对象,该对象代表了对请求的响应。你可以使用`.json()`、`.text()`等方法来处理响应内容。如果请求失败(例如网络问题),Promise会被拒绝,你可以使用`.catch()`来处理错误。 以下是几个示例的使用场景: ```javascript // 发起GET请求 fetch('https://example.com/api/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); // 发起POST请求,携带JSON格式的数据 fetch('https://example.com/api/submit', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({key: 'value'}) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); // 使用credentials选项处理跨域请求 fetch('https://example.com/api/cookie', { credentials: 'include' // 'same-origin' 或 'omit' }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

码小余の博客

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

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

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

打赏作者

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

抵扣说明:

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

余额充值