aws-mobile-react-sample开源项目

我要开发同款
匿名用户2021年12月02日
101阅读

技术信息

行业分类
云计算
开源地址
https://gitee.com/baidu/Quanlse
授权协议
Apache-2.0 License

作品详情

AWSMobileReactStarterKit

ThissampleapplicatiohasbeearchivedifavorofAmplifyJSSamples.Whilethearchivedrepositorywillstillwork,pleasego+1thisfeaturerequestforAWSMobileReactStarterKitsampleifyouarelookigtousethissample.

BootstrapaReactapplicatiooAWS.ThissampleautomaticallyprovisiosaServerlessifrastructurewithautheticatio,authorizatio,websitehostig,APIaccessaddatabaseoperatios.ItalsoicludesuserregistratioadMFAsupport.Thesampleusecaseisa"Restaurat"orderigsystemwhereafterauserregistersadlogsitheycaviewdifferetrestauratmeus,selectitemsadplaceorders.

ThisstarterusestheAWSAmplifyJavaScriptlibrarytoaddcloudsupporttotheapplicatio.

QuickliksGettigstartedBuildigaddeployigUsigRegistratioadLogicompoetsiyourAppUsigtheRESTclietiyourAppModifyigExpressroutesiLambdaforyourAppArchitectureOverview

YouwillbebuildigaReactapplicatiowithUserRegistratio&Sig-ithatallowsyoutoperformCRUDoperatiosagaistaDyamoDBtablebyusigaExpressapplicatioruigiAWSLambda.LambdawillbeivokedbyAPIGatewayusigProxyItegratiowithgreedypathsthatolyautheticateduserscaaccess.TheExpressserverisruigwiththeAWSServerlessExpressframework.

AWSServicesused:

AmazoCogitoUserPoolsAmazoCogitoFederatedIdetitiesAmazoAPIGatewayAWSLambdaAmazoDyamoDBAmazoS3AmazoCloudFrotPrerequisites

AWSAccout

NodeJSwithNPM

AWSMobileCLI

pmistall-gawsmobile-cliGettigStarted

Createyourbackedresourcesaddowloadthesamplecodeisideofmy-projectfolder.

$awsmobilestartmy-projectreact

Fiallyrutheapp:

$cdmy-project$awsmobileru

Doe!

Publishtheapp

TopublishyourapplicatiotoAmazoS3adAmazoCloudFrot:

$awsmobilepublishAlterativelyusigNPM:$pmistall$pmstart

Doe!

Eabligfederatedsig-i

Federatedsig-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.

UsigthedefaultGreetigsCompoet

Thisapplicatioisusigacustomavwithit'sowlogoutbutto.However,theAutheticatorcompoetcaprovideadefaultGreetigscompoetwhichdisplaystheuserameadalogi/logoutbutto.YoucaeablethisbyremovigtheGreetigselemetfromtheAutheticator's'hide'arrayiidex.js.

Applicatiowalkthrough

Opeabrowsertohttps://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.Buildigaddeployig

ThefollowigstepsoutliehowyoucabuildaddeploytheapplicatiousigtheS3adCloudFrotresourcescreatedbytheImportphaseabove:

Navigateto./aws-mobile-react-sample/clietadbuildforproductiobyruig:

$awsmobilepublish

Thiswillautomaticallyruthepmru-scriptbuildcommad,uploadyourapplicatiotoAmazoS3adAmazoCloudFrot,adopeyourdefaultwebbrowsertotheAmazoS3staticwebhostigpage.

AutomatigBuild&Deploy

IfyouareusigaCI/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:$awsmobilepublishAdvacedUsageUsigtheRegistratioadLogicompoetsiyourapplicatio

TheRegistratioadLogicompoetsleverageAWSAmplifytomakecallstoAmazoCogitoUserPoolsadAmazoCogitoFederatedIdetities.AsaexampleofusigitiyourowapplicatiofirstcreateaReactapplicatiowithCreateReactApp:

pmistall-gcreate-react-appcreate-react-appmy-appcdmy-app/pmstart

Iftheapplicatiorussuccessfully,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-loader

EditMai.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:

pmstart

TheapplicatioshouldstartadallowyoutoregisterusersadlogitakigyoutotheormalpagecreatedwithCreateReactApp.

UsigAWSAmplifytocommuicatewithAPIGateway

ThesampleapplicatiousesAPIGatewayadLambdatoruaExpressapplicatiowhichreadsadwritestoaDyamoDBtable.IcludedithesampleisahelperfuctioformakigsigedrequeststoAPIGateway.We'llshowhowtousethishelperformakiguautheticatedrequeststoAPIGatewaybelowadyoucausetheLogiexampleabovetogetautheticatedcredetialswhichthissamplewoulduse.

AswiththeprevioussectiofirstcreateaReactapplicatiowithCreateReactApp:

pmistall-gcreate-react-appcreate-react-appmy-appcdmy-app/pmstart

Ifyoudid'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()....morecode

Now,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-react

DepedigoifyouwattodoAutheticatedorUAutheticatedrequeststoAPIGateway,youwilleedthefollowigmodificatio:

AutheticatedRequests

Note:Ifyouaredoigaautheticated,sigedrequestyou'llalsoeedtoperformacouplemoresteps.Firstistallquerystrig-browser

pmistall--savequerystrig-browser@^1.0.4

Nextyouwilleedtocofigurethisasawebpackalias:

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});Ruyourapplicatio

Fially,aftermakigyourmodificatiosforeithertheAutheticatedorUAutheticatedrequestruthefollowigcommadtolauchyourCreateReactAppagai:

pmstart

ClickListrestauratsatthetopofthepagetousetheAWSAmplifyAPIcompoet.

ModifyigExpressroutesiLambda

ThesampleapplicatioivokesaLambdafuctioruigExpresswhichwillmakeCRUDoperatiostoDyamoDBdepedigotheroutewhichispassedfromtheclietapplicatio.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.

功能介绍

AWS Mobile React Starter Kit This sample application has been archived in favor of Amplify JS Sam...

示例图片

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论