Fetch API

Fetch API,用于在浏览器中异步访问文件或远程服务器资源。可以作为Ajax和一些第三方fetch API的替代品。它是浏览器原生支持的。

Example

    fetch(process.env.API + '/user/login', {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        method: 'POST',
        body: JSON.stringify(data),
        mode: 'cors',
        cache: 'no-cache',
        redirect: 'follow',
        credentials: 'include'
      })
        .then(async (response) => {
          if (!response.ok) {
            let err = await response.json()
            throw Error(err.message)
          }
          var contentType = response.headers.get('Content-Type')
          if (contentType && contentType.includes('application/json')) {
            return response.json()
          } else {
            throw new TypeError('Oops, we have not got JSON!')
          }
        })
        .then((json) => {
          console.log('do something when success')
        })
        .catch(function (error) {
          console.log(error.message)
          if (error.message === 'Failed to fetch') {
            self.Msg = 'network may not available'
          } else {
            self.Msg = error.message
          }
          self.isShow = true
        })

Resources