二、fetch中的基础语法

时间:2022-07-23
本文章向大家介绍二、fetch中的基础语法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

fetch概念

fetch不是Ajax,它诞生的目的是为了代替Ajax,它是js中内置的API。

基于fetch可以实现客户端和服务端的信息通信

由于fetch是2018年提出,因此存在浏览器兼容问题。

fetch('https://v1.hitokoto.cn', {
    method: 'GET',
}).then(result => {
    console.log(result);
})
fetch('https://v1.hitokoto.cn', {
            method: 'POST',
            body: 'c=b',
            headers: {
                'Content-Type': 'x-www-form-urlcoded'
            },
            credentials: 'include'
        }).then(result => {
            console.log(result);
        })

注意问题

  • GET/HEAD等请求不能设置body
  • 不管服务器返回的状态是多少,fetch都不认为是失败。并且会执行then方法。

返回结果

通过回调函数并不能直接获得响应结果。其返回结果为一个对象。

  • headers 包含响应头信息
  • redirected 是否重定向
  • status 响应码
  • statusText 响应文本
  • type basic/cors
  • url 请求地址