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

相关文章: