fetch请求的使用

一、主要特点

1、是window的一个方法;

2、第一个参数必须,是请求的url;第二个参数可选,是请求的init对象,默认请求为get;

3、使用后得到的是promise对象;

二、使用方法

1、get请求

fetch('https://...?a=1&b=2', {    //在url中传递参数
    method: 'GET',
    credentials: 'include' // 默认情况下fetch不会从服务端发送或接收任何cookies,要发送cookies,必须加入凭据头
})
.then((res)=>{
    return res.text()    //res还有json(),formData()方法
})
.catch((err)=>{
    console.log(err)
})

2、post请求

fetch('https://……', {
    method: 'POST' // 指定是POST请求
    headers: {
       'Access-Control-Allow-Origin':'*',
       'Accept': 'application/json',
       'Content-Type': 'application/x-www-form-urlencoded'    //指定提交方式为表单提交
    },
    body:"username="+this.state.username+"&password="+this.state.password    //请求对象,防止信息泄露
})
.then((res)=>{
    return res.json()    
}).catch((err)=>{
    console.log(err)
})

三、支持情况

1、Desktop

2、Mobile

四、与ajax的区别

1、ajax是利用XMLHttpRequest对象来请求数据的;

2、fetch返回的promise不会拒绝HTTP的错误状态,即使是404或500

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值