devStandard/docs/learning/3-js/2.1-fetch api.md
2025-03-29 14:35:49 +08:00

3.9 KiB
Raw Blame History

fetch api

  • ajax 是基于XMLHttpRequest 实现的, fetch 是基于 promise 原生 api
  • axios 是一个基于 Promise 的 HTTP 客户端,但它底层使用了 XMLHttpRequest
fetch("http://example.com/movies.json")
  .then((response) => response.json())
  .then((data) => console.log(data));

Fetch 比起 Axios 来讲几乎没有任何优势(除了浏览器原生支持) Fetch 是原生的 API, 并不是对 XMLHttpRequest 的封装, 类比 xhr Axios 是对 XMLHttpRequest 的封装, 是一个第三方库

语法

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

fetch(input,[init]);
// input——定义要获取的资源可以是
//  一个 USVString 字符串,包含要获取资源的 URL。
//  一个 Request 对象。

// init—— 可选 | 一个配置项对象,包括所有对请求的设置。可选的参数有:
var myInit={
    //请求的 body 信息 //如Blob、BufferSource、FormData、URLSearchParams 或者 USVString 对象
    body: JSON.stringify(data), //这里必须匹配 'Content-Type' //注意 GET 或 HEAD 方法的请求不能包含 body 信息。 
   
    //请求的 cache 模式。//如default, no-cache, reload, force-cache, only-if-cached
    cache: 'no-cache', 	 
    
    //请求的 credentials。//包括omit、same-origininclude(允许跨域请求时携带 cookie)
    credentials: 'same-origin',  
      
    //请求的头信息
    headers: {	
      'user-agent': 'Mozilla/4.0 MDN Example',
      'content-type': 'application/json'
    },
      
    //请求使用的方法  //如GET, POST, PUT, DELETE等
    method: 'POST', 
    
    //请求的模式	 //如 cors、 no-cors 或者 same-origin。
    mode: 'cors', 
      
    //重定向模式 //如 follow|自动重定向, error|如果产生重定向将自动终止并且抛出一个错误, manual|手动处理重定向
    redirect: 'follow', 
    
    //USVString  //如 no-referrer、client或一个 URL。默认是 client
    referrer: 'no-referrer',
}

get

fetch('http://example.com/movies.json')	
  .then(response => response.json())
  .then(data => console.log(data));
// 发请求获取学生信息
/**
 * fetch(): ajax的升级版
 *  参数: 1. 请求地址
 *        2. 请求信息
 * */
fetch(URL + '/api/students')
  .then(res => {
	console.log('res', res)
	// res.json(): 把响应的json对象转换成js对象, 也是返回promise
	if (res.statusText == 'OK') {
	  res.json()
	} else {
	  throw new Error('数据加载失败')
	  console.log(res.status + ' ' + res.statusText)
	}
  })
  .then(data => {
    console.log('data', data)
  })
  .catch(err => {
  	console.log(err)
  })

使用 async await

// 获取学生列表
const fetchStuList = useCallback(async () => {
  try {
    setLoading(true)
    setError(null)
    const res = await fetch(URL + '/api/students')
    if (res.statusText === 'OK') {
      const data = await res.json()
      studentsPatch({ type: 'init', data: data.data })
    } else {
      throw new Error('数据加载失败')
    }
  } catch (error) {
    setError(error.message)
  } finally {
    setLoading(false)
  }
}, [])

// 组件渲染完成后只执行一次
useEffect(() => {
  fetchStuList()
}, [])

post

var data={
    id:'1',
}
fetch('http://example.com/api',{
    method:'POST',
    headers: {
      'Content-Type': 'application/json'
  	},
    body:JSON.stringify(data)
})	
.then(response => response.json())
.then(data => console.log(data));

delete

fetch('http://example.com/movies.json',{
  method: 'DELETE'
})	
  .then(response => response.json())

表单

const formData = new FormData();  
formData.append('username', 'John');  
formData.append('email', 'john@example.com');  
  
fetch('https://example.com/api/form', {  
    method: 'POST',  
    body: formData  
})  
.then(response => response.text())  
.then(data => console.log(data))  
.catch(error => console.error('Error:', error));