本文重点在 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
© 会煮咖啡的猫咪