我的第一个全栈 Web 应用程序( 十 )
利用fetch实现数据持久化
我们可以通过fetch , 用GET方式从服务器上获得数据 , 也可以用POST方式将数据发送到服务器 。 用GET获取数据的方式可以参照前面讨论路由的时候提到的 CitiesContainer 示例 。 我们在下面的action控制器中 , 利用fetch以GET方式获取所有城市:
actions/fetchCities.jsexport const fetchCities= () = { return ( dispatch )= { fetch( 'http://localhost:3000/api/v1/cities' ) .then( response = response.json()) .then( cities = { dispatch({ type : 'FETCH_CITIES' payload :cities ) )在认证部分 , 登录action creator是一个以POST方式向服务器发送数据的例子:
actions/auth.jsexport const login= credentials = { return ( dispatch )= { fetch( 'http://localhost:3000/api/v1/login' { credentials : 'include' method : 'POST' headers :{ 'Content-Type' : 'application/json' body : JSON .stringify(credentials) ) .then( response = response.json()) .then( user = { if (user.error){ alert(user.error) else { dispatch(setCurrentUser(user)) dispatch(resetLoginForm()) ) .catch( console .log) export const setCurrentUser= user = { return { type : 'SET_CURRENT_USER' payload :user export const resetLoginForm= () = { return { type : 'RESET_LOGIN_FORM'推荐阅读
- 手机游戏|LOL手游第一个世界赛,破晓杯火热开战,DKG能紧随EDG夺冠吗?
- 我的世界|《我的世界》领衔!推荐9款低配置、超耐玩的游戏神作
- 我的世界|我的世界:主世界玩腻了?赶紧把这几个模组加入下载行列!
- 我的世界|我的世界:这些莫名其妙的设定,看起来不合理,实际却是彩蛋!
- 抖音|正在火热追我的富二代,在得知我生日后突然消失不见,到底为什么
- vg战队|我的世界:没能“活着”走出测试版本的设定,一块肉占一格空间!
- 拉克丝|嘘,我在为我的激光充能
- 我的世界|我的世界:6个“友尽”的小技巧,不要轻易在好友的服务器尝试!
- 我的世界|我的世界:“最奢侈”的附魔是什么?我给胡萝卜钓竿打上经验修补
- 原神|原神:第一个让人感觉超模的角色,主c的天花板,可持续一年!