了解fetch

关于fetch

简单的说 fetch是一种ajax的升级版替代方案,ajax的实现就是依赖xmlhttpRequest对象,而fetch是window对象的一个方法

并且实现了es6的promise来处理回调。

fetch的使用

 fetch目前除了老版本浏览器之外支持的还可以,查看fetch的支持情况

老版本浏览器也可以通过引入第三方的polyfill 来支持    whatwg-fetch

fetch的具体使用

get方法

fetch('http://localhost:8080/projectList?name=123',{
         mathod:'GET'
   }
).then(res=>{
      console.log(res.text);
}).then(res=>{
       console.log(res);
});
};

fetch方法接受两个参数,第一个必传参数就是接口的url,第二个可选参数是fetch的init项,包括method,

post方法

post传递参数要放在fetch第二个参数的body属性里面

fetch('http://localhost:8080/projectList',{
         mathod:'POST',
         body: new URLSearchParams([["foo", 1],["bar", 2]]).toString(),
         headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/x-www-form-urlencoded'
    },
   }
).then(res=>{
      console.log(res.text);
}).then(res=>{
       console.log(res);
});
};

设置请求头:

一般

fetch('http://localhost:8080/projectList?name=123',{
         mathod:'GET',
         headers: {
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': 'application/x-www-form-urlencoded'   //表单提交方式
    },
   }
).then(res=>{
      console.log(res.text);
}).then(res=>{
       console.log(res);
});
};

post请求的content-type要设置为表单提交方式

强制带cookie提交

 fetch默认是不会像服务器发送或接受cookie的,如果想提交cookie 需要再fetch的第二个参数中添加 

credentials:'include'

fetch('http://localhost:8080/projectList?name=123',{
         mathod:'GET',
         credentials: 'include', //强制带cookie发送到服务器
         headers: {
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': 'application/x-www-form-urlencoded'   //表单提交方式
    },
   }
).then(res=>{
      console.log(res.text);
}).then(res=>{
       console.log(res);
});
};

补充:

fetch是支持跨域的,只要客户端和浏览器支持

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值