fentch请求详解(发起请求与返回值)

fetch如何发起请求

  • 基础用法
fetch('/https://xxxx.xxx').then((data)=>{
  //text()属于feych的API的一部分,返回的是一个Promise实例对象,用于获取后台返回的数据
  return data.text();
}.then(data => {
  console.log(data);
}))
  • fetch请求携带参数
    • method(String):HTTP请求方法,默认为GET(GET、POST、PUT、DELETE)
    • body(String):HTTP的请求参数
    • headers(Object):HTTP的请求头,默认{}
  • GET请求方式传递参数
fetch('/https://xxxx.xxx/1234',{
  methods: 'GET'
})
.then(data => {
  return data.text();
}.then(res => {
  //最终的数据
  console.log(res);
}));
  • DELETE请求方式传递参数
fetch('/https://xxxx.xxx/1234',{
  methods: 'DELETE'
})
.then(data => {
  return data.text();
}.then(res => {
  //最终的数据
  console.log(res);
}));
  • POST请求方式传递参数
fetch('/https://xxxx.xxx',{
  methods: 'POST',
  //用于传递实际参数
  body : 'username=xxx&pwd=1234',
  //进行配置
  headers:{
    'Content-Type' : 'application/x-www-form-urlencode'
  }
})
.then(data => {
  return data.text();
}.then(res => {
  console.log(res);
}));

fench请求返回值处理

  • text():将返回体处理成字符串类型
fetch('/https://xxxx.xxx/1234',{
  methods: 'GET'
})
.then(data => {
  return data.text();
}.then(res => {
  //最终的数据
  console.log(res);
}));
  • json():返回结果和JSON.parse()样
fetch('/https://xxxx.xxx/1234',{
  methods: 'GET'
})
.then(data => {
  return data.json();
}.then(res => {
  //最终的数据
  console.log(res);
}));
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值