开源软件名称(OpenSource Name):amazon-archives/aws-mobile-react-sample开源软件地址(OpenSource Url):https://github.com/amazon-archives/aws-mobile-react-sample开源编程语言(OpenSource Language):JavaScript 93.5%开源软件介绍(OpenSource Introduction):AWS Mobile React Starter KitThis sample application has been archived in favor of Amplify JS Samples. While the archived repository will still work, please go +1 this feature request for AWS Mobile React Starter Kit sample if you are looking to use this sample. Bootstrap a React application on AWS. This sample automatically provisions a Serverless infrastructure with authentication, authorization, website hosting, API access and database operations. It also includes user registration and MFA support. The sample use case is a "Restaurant" ordering system where after a user registers and logs in they can view different restaurant menus, select items and place orders. This starter uses the AWS Amplify JavaScript library to add cloud support to the application. Quicklinks
Architecture OverviewYou will be building a React application with User Registration & Sign-in that allows you to perform CRUD operations against a DynamoDB table by using an Express application running in AWS Lambda. Lambda will be invoked by API Gateway using Proxy Integration with greedy paths that only authenticated users can access. The Express server is running with the AWS Serverless Express framework. AWS Services used:
Prerequisites
Getting Started
Done! Publish the appTo publish your application to Amazon S3 and Amazon CloudFront:
Done! Enabling federated sign-inFederated sign-in controls for Google, Facebook and Amazon are provided in the user interface by default; however, the client ids for these providers are not valid. Dummy values are provided in the You may also remove federated sign-in entirely by removing the 'federated={federated}' statement from the ReactDOM.render call in index.js. Enabling federated sign-in is a three step process:
Links to additional information about federated identity providers may be found here. Using the default Greetings ComponentThis application is using a custom nav with it's own logout button. However, the Authenticator component can provide a default Greetings component which displays the username and a login/logout button. You can enable this by removing the Greetings element from the Authenticator's 'hide' array in index.js. Application walkthrough
Alternatively, if you have enabled federated sign-in you can select the provider and skip to step 5.
Building and deployingThe following steps outline how you can build and deploy the application using the S3 and CloudFront resources created by the Import phase above:
This will automatically run the Automating Build & DeployIf you are using a CI/CD process you may choose to automate this process. The following shows how to use a webpack plugin with AWS Credentials to automate deployment to S3:
const S3Plugin = require('webpack-s3-plugin');
new S3Plugin({
// Only upload css and js
include: /.*\.(css|js)/,
// s3Options are required
s3Options: {
accessKeyId: AWS_ACCESS_KEY_ID,
secretAccessKey: AWS_SECRET_ACCESS_KEY,
},
s3UploadOptions: {
Bucket: 'MyBucket'
}
}) NOTE: Replace the
Advanced UsageUsing the Registration and Login components in your applicationThe Registration and Login components leverage AWS Amplify to make calls to Amazon Cognito User Pools and Amazon Cognito Federated Identities . As an example of using it in your own application first create a React application with Create React App:
If the application runs successfully, copy the return (
<div>
{
!logOut && (
<BrowserRouter>
<div>
<Navbar className='nav-bar' brand='WebApp' right>
<NavItem onClick={this.signOut}>Logout</NavItem>
</Navbar>
<App/>
</div>
</BrowserRouter>
)
}
{
logOut && (<AppRoute authStatus={false}/>)
}
</div>
); Next, from your
Edit //import Home from './Home';
//import Menu from './API/Menu';
//import Orders from './API/Order'; Also add Edit require('file-loader?name=[name].[ext]./index.html'); Finally to add the styling to the page edit <link rel="stylesheet" href="http://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.2/semantic.min.css"> And add the following to the body: <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/js/materialize.min.js"></script> You can now run your application created with Create React App with a new login page added:
The application should start and allow you to register users and login taking you to the normal page created with Create React App. Using AWS Amplify to communicate with API GatewayThe sample application uses API Gateway and Lambda to run an Express application which reads and writes to a DynamoDB table. Included in the sample is a helper function for making signed requests to API Gateway. We'll show how to use this helper for making unauthenticated requests to API Gateway below and you can use the Login example above to get authenticated credentials which this sample would use. As with the previous section first create a React application with Create React App:
If you didn't do the previous section, copy Edit import Link from 'link-react';
import { Table } from 'semantic-ui-react';
import awsmobile from './configuration/aws-exports';
import Amplify,{API} from 'aws-amplify';
Amplify.configure(awsmobile); ** NOTE: To make calls to API Gateway through AWS Amplify, you need your IdentityPoolID in aws-exports.js. For further documentation, refer to AWS Amplify
Modify the class App extends Component {
state = {
data: []
}
fetch = async () => {
this.setState(() => {
return {
loading: true
}
});
API.get('ReactSample','/items/restaurants')
.then(resp => {
this.setState({
data: resp
});
console.log("response is : ", resp);
})
.catch (err => console.log(err))
}
}
//render logic below
render()....more code Now, change the render() {
return (
<div className="App">
<Link onClick={this.fetch}>
List restaurants
</Link>
<div>
<div>
{(
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>Address</Table.HeaderCell>
<Table.HeaderCell>Contact</Table.HeaderCell>
<Table.HeaderCell>Rating</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{this.state.data.map((data, idx) =>
<Table.Row key={idx}>
<Table.Cell>{data.name}</Table.Cell>
<Table.Cell>{data.address}</Table.Cell>
<Table.Cell>{data.phone}</Table.Cell>
<Table.Cell>{data.rating}</Table.Cell>
</Table.Row>
)}
</Table.Body>
</Table>
)}
</div>
</div>
</div>
);
}
}
export default App; Save the file. Finally install the dependencies:
Depending on if you want to do Authenticated or UnAuthenticated requests to API Gateway, you will need the following modification: Authenticated Requests Note: If you are doing an authenticated, signed request you'll also need to perform a couple more steps. First install
Next you will need to configure this as a webpack alias: resolve: {
extensions: ['.js', '.jsx'],
alias: {
querystring: 'querystring-browser'
}
} For our Create React App sample you will need to modify either UnAuthenticated Requests Navigate to the API Gateway console, click on the ReactSample-MobileHub API and select Resources on the left hand side of the page. Under the /items node select ANY and then click on Method Request in the right hand side of the console. Click the dropdown labeled Authorization and select NONE. Press the Update tick box to save your changes. In the same part of the console, select the /items/{proxy +} node followed and click ANY and then Method Request. Repeat the process of setting Authorization to NONE and saving your change. Next deploy your changes by select Actions at the top of the page, then Deploy API and select Development as the Deployment stage. Click Deploy. Additionally you will need to make an alteration to the this.setState({
data: resp
}); To: this.setState({
data: resp.data
}); Run your applicationFinally, after making your modifications for either the Authenticated or UnAuthenticated request run the following command to launch your Create React App again:
Click List restaurants at the top of the page to use the AWS Amplify API component. Modifying Express routes in LambdaThe sample application invokes a Lambda function running Express which will make CRUD operations to DynamoDB depending on the route which is passed from the client application. You may wish to modify this backend behavior for your own needs. The steps outline how you could add functionality to "create a Restaurant" by showing what modifications would be needed in the Lambda function and the corresponding client modifications to make the request.
var putCallback = function(err, data) {
if (err) {
console.log(err)
}
}
function createMenu(restaurant_id) {
var item1 = {}
item1.id = uuid.v1()
item1.restaurant_id = restaurant_id
item1.name = "Golden Ratio Bacon Skewers"
item1.description = "Fibonacci on a stick! Who doesn’t like bacon on a stick that keeps going?"
item1.photos = []
dynamoDb.put({
Item: item1,
TableName: MENU_TABLE_NAME
}, putCallback)
var item2 = {}
item2.id = uuid.v1()
item2.restaurant_id = restaurant_id
item2.name = "Abelian Cucumber Salad"
item2.description = "A cool and refreshing salad for any hot summer day."
item2.photos = []
dynamoDb.put({
Item: item2,
TableName: MENU_TABLE_NAME
}, putCallback)
var item3 = {}
item3.id = uuid.v1()
item3.restaurant_id = restaurant_id
item3.name = "Chili-Cucumber orientable Corn"
item3.description = "Feel like you’re connected to nature with corn that wraps around your belly."
item3.photos = []
dynamoDb.put({
Item: item3,
TableName: MENU_TABLE_NAME
},< |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论