fetch简单示例笔记

这篇博客介绍了Fetch API的基本用法,作为XMLHTTPRequest和Ajax的替代,Fetch是JavaScript原生的HTTP请求方式,但需要注意其浏览器兼容性问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Fetch基本语句

fetch是原生js的一个api,是一种http数据请求的方式,是XMLHTTPRequest的一中替代方法,跟Ajax没关系。fetch是增的api,所以兼容性不是很好

<script>
    //使用fetch发送请求
    fetch('https://v1.hitokoto.cn/', {
        method: "GET"
    }).then(result => {
        console.log(result)
    }).catch(msg => {
        console.log(msg)
    });
</script>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>fetch</title>
</head>

<body>
    <p id="hitokoto_text">:D 获取中...</p>
</body>
<script>
    //使用fetch发送请求
    fetch('https://v1.hitokoto.cn', {
            //post的话就在这里面填写配置项的内容
        }).then(response => response.json())
        .then(data => {
            console.log(data)
            const hitokoto = document.getElementById('hitokoto_text')
            hitokoto.innerText = data.hitokoto
        }).catch(console.error);

    // fetch('https://v1.hitokoto.cn', {
    //     method: 'GET',
    //     //设置请求头
    //     headers: {
    //         'Content-Type': 'x-www-form-urlcoded'
    //     },
    //     //不管是同源还是跨域都带着cookie信息
    //     credentials: 'include'
    // });
    //get和head不能设置body,并且不管服务器返回的状态是什么,fetch都不认为是失败,都会接着执行then方法

</script>

</html>

注意:get和head不能设置body,并且不管服务器返回的状态是什么,fetch都不认为是失败,都会接着执行then方法

//自行解决fetch不管返回什么状态码都执行then的行为
fetch('https://v1.hitokoto.cn').then(result => {
    let {
        result
    } = result;
    if (/^(4|5)\d{2}$/.test(status)) {
        throw new Error('query data is error!');
        return;
    }
    return result.json();
}).then(result => {
    console.log(result)
}).catch(msg => {
    console.log(msg)
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值