export default ({
  url,
  method = 'get',
  data = null,
}) => {
  // 请求配置
  let options = {
    method
  }
  // data不为空时,它就是post请求
  if (data) {
    options = {
      ...options,
      body: json.stringify(data),
      headers: {
        'content-type': 'application/json'
      }
    }
  }
  return fetch(url, options)
    .then(res => res.json())
    .then(data => data)
}
 

使用

get

post 

<script type="module">
  import fetchapi from './js/fetch.js'
  const vm = new vue({
    el: '#app',
    data: {
      users: []
    },
    // 发起网络请求
    mounted() {
      let url = 'http://localhost:3000/api/users'
      // fetchapi({ url }).then(data => console.log(data))
      fetchapi({ url, method: 'post', data: { id: 200, name: 'aaa' } }).then(data => console.log(data))
    }
 
  })
</script>

以上就是fetch网络请求封装示例详解的详细内容,更多关于fetch网络请求封装的资料请关注www.887551.com其它相关文章!