学习fetch,从这里开始

一、fetch() 是什么?

fetch() 是 浏览器内置的 全局 JavaScript 方法,用于发出 http 请求,无需下载安装,可以直接使用。

// 一个简单 http 请求
fetch('http://example.com/movies.json')
    .then(function (response) {
   
        return response.json();
    })
    .then(function (myJson) {
   
        console.log(myJson);
    });

二、怎么使用?
1、简单使用实例

fetch() 的第二个参数是 init 对象,用于设置 http 的配置信息。

postData('http://example.com/answer', {
    answer: 42 })
    .then(data => console.log(data))
    .catch(error => console.error(error))

function postData(url, data) {
   
    return fetch(url, {
   
        body: JSON.stringify(data),
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
   
            'user-agent': 'Mozilla/4.0 MDN Example',
            'content-type': 'application/json'
        },
        method: 'POST',
        mode: 'cors',
        redirect: 'follow',
        referrer: 'no-referrer',
    })
        .then(response => response.json())
}
2、配置详细说明
  • method :请求使用的方法,如 GET、POST、PUT、DELETE 等。
  • headers :请求的头信息。
  • body :请求的 body 信息,注意 GET 或 HEAD 方法的请求不能包含 body 信息。
  • mode :请求模式,可用值: cors、no-cors、same-origin
  • credentials :是否发送 cookie 给服务器:omit(任何情况都不发)、same-origin(同源才发)、include(任何情况都发)
  • cache :可用 cache 模式 :default、no-store、reload、no-cache、force-cache、only-if-cached 。
  • redirect :重定向,Chrome中默认使用 follow ;
    • follow (自动重定向)
    • error (发生重定向将自动终止并且抛出错误)
    • manual (手动处理重定向)
  • referrer :发送请求的页面URL,浏览器默认添加到请求Header 中。设置成 no-referrer 表示不添加。
  • referrerPolicy :什么时候使用 referrer,可用值: no-referrer、 no-referrer-when-downgrade、origin、origin-when-cross-origin、unsafe-url 。
  • integrity :设定资源对应 hash 值,保证资源的完整性。

三、使用场景
1、发送带凭证请求
// 同不同源都会发送 带凭证的请求
fetch('https://example.com', {
   
  credentials: 'include'
})

// 只有同源才发送 带凭证请求
fetch('https://example.com', {
   
  credentials: 'same-origin'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值