fetch的使用

参考: https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

应用示例:

fetch('/api/create', { 
 method: 'POST',
 body: JSON.stringify({
  content: this.value
 }),
 headers: {
  'Content-Type': 'application/json'
 }
})
 //  .then(response => response.json())
 // .then(data => {return data});

fetch()是Web API提供的接口,用来跨网络异步获取资源(简单来说就是发起网络请求)
简单发起fetch请求后fetch('http://example.com/movies.json'),返回一个包含响应结果的 promise(一个 Response 对象)。只是一个 HTTP 响应,而不是真的 JSON。为了获取JSON的内容,我们需要使用 json() 方法处理第一个返回.then(response => response.json()),此时得到的response包含json对象,通过 .then(data => {return data});获取到返回的数据。

  • 总结:第一个返回的是http请求,第二个返回的是数据,必须要用json()处理第一个返回,才能得到第二个返回的json数据,不然获取不到。
  • 补充:转化为JSON的方法很多,有需要自行查找::JSON.parse(_todos),.json()
posted @ 2022-05-17 15:16  黑蛋的博客  阅读(135)  评论(0编辑  收藏  举报