AWSMobileReactStarterKit
ThissampleapplicatiohasbeearchivedifavorofAmplifyJSSamples.Whilethearchivedrepositorywillstillwork,pleasego+1thisfeaturerequestforAWSMobileReactStarterKitsampleifyouarelookigtousethissample.
BootstrapaReactapplicatiooAWS.ThissampleautomaticallyprovisiosaServerlessifrastructurewithautheticatio,authorizatio,websitehostig,APIaccessaddatabaseoperatios.ItalsoicludesuserregistratioadMFAsupport.Thesampleusecaseisa"Restaurat"orderigsystemwhereafterauserregistersadlogsitheycaviewdifferetrestauratmeus,selectitemsadplaceorders.
ThisstarterusestheAWSAmplifyJavaScriptlibrarytoaddcloudsupporttotheapplicatio.
QuickliksGettigstartedBuildigaddeployigUsigRegistratioadLogicompoetsiyourAppUsigtheRESTclietiyourAppModifyigExpressroutesiLambdaforyourAppArchitectureOverviewYouwillbebuildigaReactapplicatiowithUserRegistratio&Sig-ithatallowsyoutoperformCRUDoperatiosagaistaDyamoDBtablebyusigaExpressapplicatioruigiAWSLambda.LambdawillbeivokedbyAPIGatewayusigProxyItegratiowithgreedypathsthatolyautheticateduserscaaccess.TheExpressserverisruigwiththeAWSServerlessExpressframework.
AWSServicesused:
AmazoCogitoUserPoolsAmazoCogitoFederatedIdetitiesAmazoAPIGatewayAWSLambdaAmazoDyamoDBAmazoS3AmazoCloudFrotPrerequisitesAWSAccout
NodeJSwithNPM
AWSMobileCLI
pmistall-gawsmobile-cliGettigStartedCreateyourbackedresourcesaddowloadthesamplecodeisideofmy-projectfolder.
$awsmobilestartmy-projectreactFiallyrutheapp:
$cdmy-project$awsmobileruDoe!
PublishtheappTopublishyourapplicatiotoAmazoS3adAmazoCloudFrot:
$awsmobilepublishAlterativelyusigNPM:$pmistall$pmstartDoe!
Eabligfederatedsig-iFederatedsig-icotrolsforGoogle,FacebookadAmazoareprovideditheuseriterfacebydefault;however,theclietidsfortheseprovidersareotvalid.Dummyvaluesareprovidedithefederatedobjectwithiidex.jssothattheuseriterfacecotrolsappear.Youcaremoveayofthecotrolsbydeletigtheappropriatekeysfromthefederatedobject.
Youmayalsoremovefederatedsig-ietirelybyremovigthe'federated={federated}'statemetfromtheReactDOM.redercalliidex.js.
Eabligfederatedsig-iisathreestepprocess:
Registeryourapplicatiowiththeprovider(s).
Theidetityproviderswillrequestiformatioaboutyourapplicatio,adwillsupplyyouwithaapplicatioIDadotherkeysthatyourapplicatio(s)willuseforautheticatio.KeepimidthatsomeprovidersmaysupplyseparateapplicatioIDsformultipleapplicatiosevewhetheseapplicatiosaresharigAWSresources.
Eabletheproviderforyourapplicatio.
Therearemultiplewaysofeabligafederatedidetityproviderforyourapplicatio.
TheAWSMobileCLIprovidescommadsforeabligproviders.
$awsmobileuser-sigieable$awsmobileuser-sigicofigureIfyouselectFacebook:?FacebookAppIDxxxxxxxIfyouselectGoogle:?GoogleWebAppClietIDxxxxxxx?GoogleAdroidClietIDxxxxxxx?GoogleiOSClietIDxxxxxxx$awsmobilepushAWSMobileHuballowsyoutoregisteraidetityproviderbyaccessigtheUserSig-IsectioadselectigtheproviderudertheAddsig-iProviderssectio.TheAWSCogitoadIAMCosolesallowyoutoregisteridetityprovidersaswell.Pleaseseetherespectivedocumetatiofortheseservices.Oceyouhaveregisteredyourapplicatiowithyourfederatedidetityprovider(s)adhaveeabledfederatedidetityforyourapplicatio,makesuretoicludeyourclietidsithefederatedobjectiidex.js.Likstoadditioaliformatioaboutfederatedidetityprovidersmaybefoudhere.
UsigthedefaultGreetigsCompoetThisapplicatioisusigacustomavwithit'sowlogoutbutto.However,theAutheticatorcompoetcaprovideadefaultGreetigscompoetwhichdisplaystheuserameadalogi/logoutbutto.YoucaeablethisbyremovigtheGreetigselemetfromtheAutheticator's'hide'arrayiidex.js.
ApplicatiowalkthroughOpeabrowsertohttps://localhost:8080adviewtheAutheticatorcompoet.ChooseSigUpNowadtypeiauserame,password,emailaddressadphoeumber.Alteratively,ifyouhaveeabledfederatedsig-iyoucaselecttheprovideradskiptostep5.
Youshouldrecievea6-digitverificatiocodeviaSMS.TypethisitothescreeadselectValidate.
NowthatyouareregisteredyouwillberedirectedtotheLogipage.TypeitheuserameadpasswordtheselectLogi.
YouwillrecieveaotherSMSverificatiocode.ThisistheMFAflowupouserlogi.EterthecodeitothescreeadselectValidate.
Theapplicatiodemostratesbothloadigsampledataitothedatabaseaswellaslistigdataadavigatio.AsafirsttimeuserpressIsertRestauratstoloadsamplerestauratsitotheapplicatio.
ThesampledataisstoredisidetheimportedLambdafuctio(iit.js).ThisdemostrateshowLambdacodecabeusedwithExpresstoisertrecordsitoDyamoDB.TherequestfromthecliettoAPIGatewayissigedusigAWSSigatureVersio4withthecredetialsreturedfromAmazoCogitowhetheuserloggeditotheapplicatio.Refertotheadvacedsectioofthisdocumetformoreiformatioousigthisiyourdesigs.NowthatdatahasbeeloadedselectListRestauratstodisplaythelistofrestauratsthatwereaddedithepreviousstep.Thisalsousesthesigigprocessdescribedabove.
Clickotheameofarestaurattoseeameu.
PressOrdertoplaceaorderithesystem.ThiswilladdaorderetrytoaDyamoDBtableaswellasstoreiformatioithelocalbrowserfortrackig.
PressOrdersitheavigatiobar.YouwillseesomeiformatioimmediatelyfromlocalstorageadotheriformatioreturedasychroouslyfromacalltoAPIGateway.
Theavigatiobarisoptimizedtoworkacrossdesktopadmobilebrowsers.ItwillshoweitheratthetopofthepageoriacollapsiblebarotheleftformobileformfactorsSelectLogoutitheavigatiobartoreturtheusertothehomepage.BuildigaddeployigThefollowigstepsoutliehowyoucabuildaddeploytheapplicatiousigtheS3adCloudFrotresourcescreatedbytheImportphaseabove:
Navigateto./aws-mobile-react-sample/clietadbuildforproductiobyruig:
$awsmobilepublish
Thiswillautomaticallyruthepmru-scriptbuildcommad,uploadyourapplicatiotoAmazoS3adAmazoCloudFrot,adopeyourdefaultwebbrowsertotheAmazoS3staticwebhostigpage.
AutomatigBuild&DeployIfyouareusigaCI/CDprocessyoumaychoosetoautomatethisprocess.ThefollowigshowshowtouseawebpackplugiwithAWSCredetialstoautomatedeploymettoS3:
Navigateto./aws-mobile-react-sample/cliet/directoryadeditwebpack.cofig.jsfile.Addthefollowigtothetopofthefile:costS3Plugi=require('webpack-s3-plugi');Addthefollowigasaetrytotheplugis:[]sectiotowardsthebottom:ewS3Plugi({//Olyuploadcssadjsiclude:/.*\.(css|js)/,//s3Optiosarerequireds3Optios:{accessKeyId:AWS_ACCESS_KEY_ID,secretAccessKey:AWS_SECRET_ACCESS_KEY,},s3UploadOptios:{Bucket:'MyBucket'}})NOTE:ReplacetheAWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEYadMyBucketwithappropriatevaluessuchasyouraccoutkeysforautomatioadtheS3bucketcreateddurigtheimportprocess.
Savethefileadruthefollowigcommadtoistalltheplugidepedecy:pmistall--savewebpack-s3-plugiRuthefollowigcommadtobuildaddeploytoS3:$awsmobilepublishAdvacedUsageUsigtheRegistratioadLogicompoetsiyourapplicatioTheRegistratioadLogicompoetsleverageAWSAmplifytomakecallstoAmazoCogitoUserPoolsadAmazoCogitoFederatedIdetities.AsaexampleofusigitiyourowapplicatiofirstcreateaReactapplicatiowithCreateReactApp:
pmistall-gcreate-react-appcreate-react-appmy-appcdmy-app/pmstartIftheapplicatiorussuccessfully,copytheAuth,cofiguratioadcssfoldersfrom./aws-mobile-react-sample/cliet/srcto./my-app/srcthatwascreatedbyCreateReactApp.Nextcopyidex.jsadMai.jsxfrom./aws-mobile-react-sample/cliet/srcto./my-app/src.EditthecopiedMai.jsxsothattheretur()fuctiomatchesthebelowcode:
retur(<div>{!logOut&&(<BrowserRouter><div><NavbarclassName='av-bar'brad='WebApp'right><NavItemoClick={this.sigOut}>Logout</NavItem></Navbar><App/></div></BrowserRouter>)}{logOut&&(<AppRouteauthStatus={false}/>)}</div>);Next,fromyour./my-appdirectory,ru:
$pmistall--saveaws-amplifyreact-router-domreact-materializereact-trasitio-group@^1.1.3sematic-ui-reactcss-loaderEditMai.jsxadcommetoutthefollowig:
//importHomefrom'./Home';//importMeufrom'./API/Meu';//importOrdersfrom'./API/Order';AlsoaddimportAppfrom'./App';tothetopofMai.jsxadsavethefile.
Editidex.jsadreplacetherequire('file-loader....')statemettowardsthetopwith:
require('file-loader?ame=[ame].[ext]./idex.html');Fiallytoaddthestyligtothepageedit./my-app/public/idex.htmladaddthefollowigtothehead:
<likrel="stylesheet"href="https://fots.googleapis.com/ico?family=Material+Icos"><likrel="stylesheet"href="https://cdjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.mi.css"><likrel="stylesheet"href="https://cdjs.cloudflare.com/ajax/libs/sematic-ui/2.2.2/sematic.mi.css">Adaddthefollowigtothebody:
<scriptsrc="https://code.jquery.com/jquery-2.1.1.mi.js"></script><scriptsrc="https://cdjs.cloudflare.com/ajax/libs/materialize/0.98.0/js/materialize.mi.js"></script>YoucaowruyourapplicatiocreatedwithCreateReactAppwithaewlogipageadded:
pmstartTheapplicatioshouldstartadallowyoutoregisterusersadlogitakigyoutotheormalpagecreatedwithCreateReactApp.
UsigAWSAmplifytocommuicatewithAPIGatewayThesampleapplicatiousesAPIGatewayadLambdatoruaExpressapplicatiowhichreadsadwritestoaDyamoDBtable.IcludedithesampleisahelperfuctioformakigsigedrequeststoAPIGateway.We'llshowhowtousethishelperformakiguautheticatedrequeststoAPIGatewaybelowadyoucausetheLogiexampleabovetogetautheticatedcredetialswhichthissamplewoulduse.
AswiththeprevioussectiofirstcreateaReactapplicatiowithCreateReactApp:
pmistall-gcreate-react-appcreate-react-appmy-appcdmy-app/pmstartIfyoudid'tdotheprevioussectio,copycofiguratiofrom./aws-mobile-react-sample/cliet/srcto./my-app/src.
Edit./my-app/src/App.jswiththefollowigimportsatthetop:
importLikfrom'lik-react';import{Table}from'sematic-ui-react';importawsmobilefrom'./cofiguratio/aws-exports';importAmplify,{API}from'aws-amplify';Amplify.cofigure(awsmobile);**NOTE:TomakecallstoAPIGatewaythroughAWSAmplify,youeedyourIdetityPoolIDiaws-exports.js.Forfurtherdocumetatio,refertoAWSAmplifyModifytheAppcompoetlikeso(NOTE:youareNOTmodifyigtherederfuctioYET):
classAppextedsCompoet{state={data:[]}fetch=asyc()=>{this.setState(()=>{retur{loadig:true}});API.get('ReactSample','/items/restaurats').the(resp=>{this.setState({data:resp});cosole.log("resposeis:",resp);}).catch(err=>cosole.log(err))}}//rederlogicbelowreder()....morecodeNow,chagethereder()fuctiolikeso:
reder(){retur(<divclassName="App"><LikoClick={this.fetch}>Listrestaurats</Lik><div><div>{(<Table><Table.Header><Table.Row><Table.HeaderCell>Name</Table.HeaderCell><Table.HeaderCell>Address</Table.HeaderCell><Table.HeaderCell>Cotact</Table.HeaderCell><Table.HeaderCell>Ratig</Table.HeaderCell></Table.Row></Table.Header><Table.Body>{this.state.data.map((data,idx)=><Table.Rowkey={idx}><Table.Cell>{data.ame}</Table.Cell><Table.Cell>{data.address}</Table.Cell><Table.Cell>{data.phoe}</Table.Cell><Table.Cell>{data.ratig}</Table.Cell></Table.Row>)}</Table.Body></Table>)}</div></div></div>);}}exportdefaultApp;Savethefile.Fiallyistallthedepedecies:
pmistall--savelik-reactsematic-ui-reactDepedigoifyouwattodoAutheticatedorUAutheticatedrequeststoAPIGateway,youwilleedthefollowigmodificatio:
AutheticatedRequests
Note:Ifyouaredoigaautheticated,sigedrequestyou'llalsoeedtoperformacouplemoresteps.Firstistallquerystrig-browser
pmistall--savequerystrig-browser@^1.0.4Nextyouwilleedtocofigurethisasawebpackalias:
resolve:{extesios:['.js','.jsx'],alias:{querystrig:'querystrig-browser'}}ForourCreateReactAppsampleyouwilleedtomodifyeitherwebpack.cofig.dev.jsorwebpack.cofig.prod.jsithe./my-app/ode_modules/react-scripts/cofigdirectory.Lookfortheresolve:fieldisidemodule.exportsadaddthequerystrig:'querystrig-browser'etryuderthealiasfield.
UAutheticatedRequests
NavigatetotheAPIGatewaycosole,clickotheReactSample-MobileHubAPIadselectResourcesothelefthadsideofthepage.Uderthe/itemsodeselectANYadtheclickoMethodRequestitherighthadsideofthecosole.ClickthedropdowlabeledAuthorizatioadselectNONE.PresstheUpdatetickboxtosaveyourchages.
Ithesamepartofthecosole,selectthe/items/{proxy+}odefollowedadclickANYadtheMethodRequest.RepeattheprocessofsettigAuthorizatiotoNONEadsavigyourchage.
NextdeployyourchagesbyselectActiosatthetopofthepage,theDeployAPIadselectDevelopmetastheDeploymetstage.ClickDeploy.
Additioallyyouwilleedtomakeaalteratiotothe./my-app/src/App.jsbychagigthethis.setState()fuctiofrom:
this.setState({data:resp});To:
this.setState({data:resp.data});RuyourapplicatioFially,aftermakigyourmodificatiosforeithertheAutheticatedorUAutheticatedrequestruthefollowigcommadtolauchyourCreateReactAppagai:
pmstartClickListrestauratsatthetopofthepagetousetheAWSAmplifyAPIcompoet.
ModifyigExpressroutesiLambdaThesampleapplicatioivokesaLambdafuctioruigExpresswhichwillmakeCRUDoperatiostoDyamoDBdepedigotheroutewhichispassedfromtheclietapplicatio.Youmaywishtomodifythisbackedbehaviorforyouroweeds.Thestepsoutliehowyoucouldaddfuctioalityto"createaRestaurat"byshowigwhatmodificatioswouldbeeededitheLambdafuctioadthecorrespodigclietmodificatiostomaketherequest.
Addthefollowigfuctioitoapp.jsbeforethesectiothatsays*Restauratmethods*varputCallback=fuctio(err,data){if(err){cosole.log(err)}}fuctiocreateMeu(restaurat_id){varitem1={}item1.id=uuid.v1()item1.restaurat_id=restaurat_iditem1.ame="GoldeRatioBacoSkewers"item1.descriptio="Fiboaccioastick!Whodoes’tlikebacooastickthatkeepsgoig?"item1.photos=[]dyamoDb.put({Item:item1,TableName:MENU_TABLE_NAME},putCallback)varitem2={}item2.id=uuid.v1()item2.restaurat_id=restaurat_iditem2.ame="AbeliaCucumberSalad"item2.descriptio="Acooladrefreshigsaladforayhotsummerday."item2.photos=[]dyamoDb.put({Item:item2,TableName:MENU_TABLE_NAME},putCallback)varitem3={}item3.id=uuid.v1()item3.restaurat_id=restaurat_iditem3.ame="Chili-CucumberorietableCor"item3.descriptio="Feellikeyou’recoectedtoaturewithcorthatwrapsaroudyourbelly."item3.photos=[]dyamoDb.put({Item:item3,TableName:MENU_TABLE_NAME},putCallback)varitem4={}item4.id=uuid.v1()item4.restaurat_id=restaurat_iditem4.ame="FiiteShort-RibFields"item4.descriptio="Noutesils!BBQisfigerfood!"item4.photos=[]dyamoDb.put({Item:item4,TableName:MENU_TABLE_NAME},putCallback)varitem5={}item5.id=uuid.v1()item5.restaurat_id=restaurat_iditem5.ame="EasyFractalSalad"item5.descriptio="Thissymmetricpastasaladfeaturesfeta,artichokehearts,adkale."item5.











评论