本文重點在 fetch
基礎使用、配置、實戰,若是你很熟練了,能夠直接 pass前端
掌握 fetch
使用node
我在 easy-mock
上準備了模擬數據react
https://www.easy-mock.com/moc...ios
[ { "id": "610000200102261253", "name": "薛洋" }, { "id": "350000199603020600", "name": "許磊" }, { "id": "310000198105081812", "name": "崔娟" }, { "id": "820000197101010860", "name": "石霞" } ]
一個列表,兩個字段 id
name
git
fetch( 'https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/all' ) .then(res => res.json()) .then(data => { console.log(data) this.setState({users: data}) }) .catch(e => console.log('錯誤:', e))
fetch
是瀏覽器內置對象,因此咱們不用安裝包,直接使用github
使用流程json
注意須要執行一次
res.json()
方法才能獲取數據
咱們獲取數據後,設置 state
,而後正常數據 render
就行,完整代碼redux
import React, {Component} from 'react' class RequestView extends Component { constructor(props) { super(props) this.state = {users: []} this.handleClick = this.handleClick.bind(this) } handleClick() { fetch( 'https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/all' ) .then(res => res.json()) .then(data => { console.log(data) this.setState({users: data}) }) .catch(e => console.log('錯誤:', e)) } render() { return ( <div> <input type="button" value="點擊 http-get 方式獲取數據" onClickCapture={this.handleClick} /> <ul> {this.state.users && this.state.users.map((item, index) => ( <li key={index.toString()}>{item.name}</li> ))} </ul> </div> ) } }
打印axios
https://codepen.io/ducafecat/...segmentfault
咱們來好好的看下這個 fetch()
全局方法
我舉兩個自定義例子,你們體會下
Headers
請求頭協議說明let initHeaders = new Headers() initHeaders.append('Accept', 'application/json, text/plain, */*') initHeaders.append('Cache-Control', 'no-cache') initHeaders.append('Content-Type', 'application/x-www-form-urlencoded')
application/x-www-form-urlencoded
init
配置let data = {uid: 1011} let body = `uid=${data.uid}` const init = { method: 'POST', credentials: 'include', // cookies cache: 'no-cache ', // cookies headers: initHeaders, body }
method
指定 POST
方式credentials: 'include'
表示每次都帶上 cookies
headers
請求頭協議說明body
數據,格式 key=val&key=val&key=val
fetch( 'https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/login', init ) .then(res => res.json()) .then(data => { this.setState({user: data}) }) .catch(e => console.log('錯誤:', e))
這裏就相似咱們第一個基礎例子了
https://codepen.io/ducafecat/...
Headers
let initHeaders = new Headers() initHeaders.append('Accept', 'application/json, text/plain, */*') initHeaders.append('Cache-Control', 'no-cache') initHeaders.append('Content-Type', 'application/json;charset=UTF-8')
Content-Type
類型須要定義成 application/json;charset=UTF-8
init
let data = {uid: 1011} let body = JSON.stringify(data, null, 2) const init = { method: 'POST', credentials: 'include', // cookies cache: 'no-cache ', // cookies headers: initHeaders, body }
json
數據須要格式化 JSON.stringify(data, null, 2)
fetch( 'https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/login', init ) .then(res => res.json()) .then(data => { this.setState({user: data}) }) .catch(e => console.log('錯誤:', e))
https://codepen.io/ducafecat/...
代碼
import React, {Component} from 'react' class RequestView extends Component { constructor(props) { super(props) this.state = {user: null} this.handlePostForm = this.handlePostForm.bind(this) this.handlePostJSON = this.handlePostJSON.bind(this) } handlePostForm() { let initHeaders = new Headers() initHeaders.append('Accept', 'application/json, text/plain, */*') initHeaders.append('Cache-Control', 'no-cache') initHeaders.append('Content-Type', 'application/x-www-form-urlencoded') let data = {uid: 1011} let body = `uid=${data.uid}` const init = { method: 'POST', credentials: 'include', // cookies cache: 'no-cache ', // cookies headers: initHeaders, body } fetch( 'https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/login', init ) .then(res => res.json()) .then(data => { this.setState({user: data}) }) .catch(e => console.log('錯誤:', e)) } handlePostJSON() { let initHeaders = new Headers() initHeaders.append('Accept', 'application/json, text/plain, */*') initHeaders.append('Cache-Control', 'no-cache') initHeaders.append('Content-Type', 'application/json;charset=UTF-8') let data = {uid: 1011} let body = JSON.stringify(data, null, 2) const init = { method: 'POST', credentials: 'include', // cookies cache: 'no-cache ', // cookies headers: initHeaders, body } fetch( 'https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/login', init ) .then(res => res.json()) .then(data => { this.setState({user: data}) }) .catch(e => console.log('錯誤:', e)) } render() { return ( <div> <input type="button" value="點擊 http-post form 表單" onClickCapture={this.handlePostForm} /> <br /> <input type="button" value="點擊 http-post json raw 格式" onClickCapture={this.handlePostJSON} /> {this.state.user && ( <ul> <li>ID: {this.state.user.id}</li> <li>Name: {this.state.user.name}</li> </ul> )} </div> ) } } export default RequestView
動圖效果
async / wait
async handleClick() { try { const res = await fetch( 'https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/all' ) const users = await res.json() this.setState({users}) } catch (error) { console.log('錯誤', error) } }
async
res.json()
這個方法不要忘記調用try ... catch ...
代碼
import React, {Component} from 'react' class RequestView extends Component { constructor(props) { super(props) this.state = {users: []} this.handleClick = this.handleClick.bind(this) } async handleClick() { try { const res = await fetch( 'https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/all' ) const users = await res.json() this.setState({users}) } catch (error) { console.log('錯誤', error) } } render() { return ( <div> <input type="button" value="點擊 async / await 方式獲取數據" onClickCapture={this.handleClick} /> <ul> {this.state.users && this.state.users.map((item, index) => ( <li key={index.toString()}>{item.name}</li> ))} </ul> </div> ) } } export default RequestView
打印
好像 fetch
很強啊,不用安裝包,全局方法直接用,可是有一個小問題,對瀏覽器的依賴,先看下 caniuse 平臺的報告:
IE
全陣亡,低版本 Safari
兼容問題,Firefox
Chrome
Opera
若是特性不開的話也會出問題,懂的同窗說能夠瀏覽器配置和打 polyfill
補丁,可是這樣須要本身作不少工做,若是你的代碼須要跑到 node
端呢(由於API 業務層
頗有可能複用性很高)。
若是考慮兼容性,因此咱們仍是用第三方組件
感受 Star
不是不少麼。。。
接着往下看
README 裏說了各類平臺支持、知名項目也在用
是真的麼。。。
接着往下看
打開文件 package.json
來看下這兩個包
https://github.com/bitinn/nod...
指向了 github/fetch
https://github.com/github/fetch
好多 Star 看着就放心,你們用吧
yarn add cross-fetch
import React, {Component} from 'react' import fetch from 'cross-fetch' class RequestView extends Component { constructor(props) { super(props) this.state = {users: []} this.handleClick = this.handleClick.bind(this) } async handleClick() { try { const res = await fetch( 'https://www.easy-mock.com/mock/59801fd8a1d30433d84f198c/example/user/all' ) const users = await res.json() this.setState({users}) } catch (error) { console.log('錯誤', error) } } render() { return ( <div> <input type="button" value="點擊 cross-fetch 組件方式 獲取數據" onClickCapture={this.handleClick} /> <ul> {this.state.users && this.state.users.map((item, index) => ( <li key={index.toString()}>{item.name}</li> ))} </ul> </div> ) } } export default RequestView
© 會煮咖啡的貓咪