TypeScript使用Fetch请求接口

Fetch API是XMLHttpRequest的升级版,浏览器原生提供,用于发送HTTP请求,属于HTML5新增的API。

参数说明:

// async
const response = await fetch(url, {
  method: "GET", // http请求方法,GET/POST/DELETE/PUT等
  headers: { // 请求头配置
    "Content-Type": "text/plain;charset=UTF-8"
  },
  body: undefined, // 请求数据体
  referrer: "about:client", // 请求来源标识
  referrerPolicy: "no-referrer-when-downgrade", // 指定referrer的规则
  mode: "cors", // 指定请求的模式,默认cors,支持same-origin、no-cors
  credentials: "same-origin", // 指定是否发送Cookie,默认same-origin,支持include、omit
  cache: "default", // 指定如何处理缓存,默认default,支持no-store、reload、no-cache、force-cache、only-if-cached
  redirect: "follow", // 指定HTTP跳转的处理方式,默认follow,支持error、manual
  integrity: "", // 指定一个哈希值,用于检查HTTP响应的是否为这个预设的哈希值
  keepalive: false, // 页面卸载时,是否通知后台保持连接
  signal: undefined, // 指定AbortSignal实例,用于取消fetch请求
})

GET请求:

// GET
fetch('http://example.com/userInfo?uid=1')
  .then((response) => {
    return response.json();
  })
  .then((e) => {
    console.log(e);
  });

// 或者
const response = await fetch("http://example.com/userInfo?uid=1");
console.log(await response.json());

POST请求:

// POST
fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  body: JSON.stringify(jsonData)
})
  .then(response => {
    return response.json()
  })
  .then(e => {
    console.log(e)
  })
  .catch(err => {
    console.error(err)
  })

响应处理:

1、通过Response对象的状态码判断状态:

const res = await fetch(url)
if (res.status >= 200 && res.status < 300) {
  return await res.text()
}
else {
  return new Error(res.statusText)
}

2、通过Response对象的ok参数判断(对应状态码200-299)

// async
const res = await fetch(url)
if (res.ok) {
  return await res.text()
}
else {
  return new Error(res.statusText)
}

3、读取返回内容

// async
const res = awati fetch(url, {
  headers: {
    "Content-Type": "text/plain;charset=UTF-8"
  }
})
//text数据
if(res.headers.get("content-type") === 'text/plain') {
  return await res.text()
}
//json数据
if(res.headers.get("content-type") === 'application/json') {
  return await res.json()
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值