我的第一个全栈 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'

推荐阅读