在 AWS Amplify 上部署 Web 应用程序
入门指南
模块 2:构建前端并连接 API
在本模块中,您将学习向 Amplify 项目添加 API
简介
在本模块中,您将为自己的 Web 应用程序构建前端并使用 GraphQL API 连接到 API (应用程序编程接口)。GraphQL 是一种 API 查询语言,可帮助您检索和更新应用程序上的数据。
您将学到的内容
- 创建基本的 React 前端应用程序
- 从您的应用程序调用 GraphQL API
- 从应用程序的前端调用 API
完成时间
10 分钟
模块先决条件
- 具有管理员级访问权限的 AWS 账户**
- 推荐的浏览器:最新版 Chrome 或 Firefox
[**] 过去 24 小时内创建的账户可能尚不具有访问此教程所需服务的权限。
实施
安装 Amplify 库
您需要安装 Amplify React 库 @aws-amplify/ui-react (包含 React UI 组件)。
运行以下命令安装它们:
npm install @aws-amplify/ui-react
您现在需要为应用程序创建前端。打开 src/App.js file 文件并将其全部内容替换为以下代码:
import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react';
import Amplify from 'aws-amplify';
import awsExports from './aws-exports';
Amplify.configure(awsExports);
function App() {
return (
<div>
<h1>Notes App</h1>
<AmplifySignOut />
</div>
);
}
export default withAuthenticator(App);
测试应用程序
现在您可以在本地运行应用程序来进行测试:
npm start
这将在 http://localhost:3000 上启动开发服务器并在浏览器中打开页面。在可以使用该服务之前,系统会提示您注册 - 此数据存储在您项目的 Congnito 数据库中,只有您有权访问它。登录后,该应用程序将仅显示带有 Notes App 的标题和登录按钮,这是因为您尚未向其中添加任何内容。接下来,您将向应用程序添加 API。您可以使用 ctrl + c 再次停止服务器。

只需几条 CLI 命令和几行代码,我们就创建了一个带登录流程的有效单页面应用程序。此应用程序目前只是一个框架,登录尚未起作用。在以下部分中继续向您的应用程序添加功能。
使用 Amplify 添加 GraphQL API
您现在将向应用程序添加 API。Amplify 使用 AWS AppSync 和 Amazon DynamoDB 来支持 GraphQL API。AppSync 是托管的 GraphQL 服务,它将负责处理我们的 AP;而 Amazon DynamoDB 是 NoSQL 数据库,它存储我们的 API 将使用的数据。
要添加 API,请运行 amplify add api,然后为问题选择以下选项 (行以 > 符号开头) - 在此步骤中,它将询问有关授权提供商的问题,此信息将在以后的指南中使用:
GraphQL 架构是对象及其字段的表示。您需要定义 GraphQL 架构,而 Amplify 将创建所需的 DynamoDB 表,并配置 GraphQL 来自动处理读取、写入、更新和删除。打开 amplify/backend/api/amplifyapp/schema.graphql 文件并将内容替换为以下代码:
amplify add api
? Please select from one of the below mentioned services:
❯ GraphQL
REST
? Provide API name: amplifyapp
? Choose the default authorization type for the API
API key
❯ Amazon Cognito User Pool
IAM
OpenID Connect
? Do you want to configure advanced settings for the GraphQL API
? Do you want to use the default authentication and security configuration?
❯ Default configuration
Default configuration with Social Provider (Federation)
Manual configuration
I want to learn more.
? How do you want users to be able to sign in?
◯ Email
❯◉ Username
◯ Phone number
? Do you want to configure advanced settings?
❯ No, I am done.
Yes, I want to make some additional changes.
? Do you have an annotated GraphQL schema? No
? Choose a schema template:
❯ Single object with fields (e.g., “Todo” with ID, name, description)
One-to-many relationship (e.g., “Blogs” with “Posts” and “Comments”)
Objects with fine-grained access control (e.g., a project management app with owner-bas
ed authorization)
? Do you want to edit the schema now? Yes
创建 GraphQL 架构
GraphQL 架构是对象及其字段的表示。您需要定义 GraphQL 架构,而 Amplify 将创建所需的 DynamoDB 表,并配置 GraphQL 来自动处理读取、写入、更新和删除。打开 amplify/backend/api/amplifyapp/schema.graphql 文件并将内容替换为以下代码:
type Note @model @auth(rules: [{ allow: owner }]) {
id: ID!
text: String!
}
此架构定义了一个以 id 和文本作为必填字段的备注类型。它还包含若干指令,这些指令属于 Amplify 的 GraphQL 转换库:
@model:以 @model 注释的类型存储在 DynamoDB 中,系统自动为其创建 CRUDL (创建、读取、更新、删除、列表) 操作。
@auth:以 @auth 注释的类型受一组授权规则的保护。在这里,我们使用拥有者授权来确保只有备注的拥有者才能访问和修改。
部署应用程序
您现在准备好通过运行 amplify push 来部署自己的 Amplify Web 应用程序。这会将您的应用程序上传到自己的 AWS 账户,而 Amplify 将向您显示正在部署的更改,并要求确认部署:
✔ Successfully pulled backend environment dev from the cloud.
Current Environment: dev
┌──────────┬────────────────────┬───────────┬───────────────────┐
│ Category │ Resource name │ Operation │ Provider plugin │
├──────────┼────────────────────┼───────────┼───────────────────┤
│ Auth │ amplifyapp6177aede │ Create │ awscloudformation │
├──────────┼────────────────────┼───────────┼───────────────────┤
│ Api │ amplifyapp │ Create │ awscloudformation │
└──────────┴────────────────────┴───────────┴───────────────────┘
? Are you sure you want to continue? Yes
确认后,根据提示选择后续问题的原定设置值:
? Do you want to generate code for your newly created GraphQL API Yes
? Choose the code generation language target javascript
? Enter the file name pattern of graphql queries, mutations and subscriptions src/graphql/**/*.js
? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions Yes
? Enter maximum statement depth [increase from default if your schema is deeply nested] 2
这将需要几分钟的时间来完成部署,期间将看到正在创建的资源列表。Amplify 执行以下操作:
- 创建一个由 AWS AppSync 提供支持的 GraphQL API,其中包含所有三种类型的 GraphQL 操作 (查询、突变和订阅)。
- 使用创建、检索和更新备注所需的 GraphQL 操作在 src/graphql/ 文件夹中生成代码。
- 创建 DynamoDB 表来存储使用应用程序创建的任何备注。
更新前端以使用 API
要使用您刚刚部署的新 API,请通过将其中的内容替换为以下代码来更新 src/App.js 文件:
import { Component } from 'react';
import Amplify, { API, graphqlOperation } from 'aws-amplify';
import { createNote, deleteNote } from './graphql/mutations';
import { listNotes } from './graphql/queries';
import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react';
import awsExports from './aws-exports';
Amplify.configure(awsExports);
class AddNote extends Component {
constructor(props) {
super(props);
this.state = { text: '' };
}
handleChange = (event) => {
this.setState({ text: event.target.value });
}
handleClick = () => {
this.props.addNote(this.state);
this.setState({ text: '' });
}
render() {
return (
<div style={styles.form}>
<input
value={this.state.text}
onChange={this.handleChange}
placeholder="New Note"
style={styles.input}
/>
<button onClick={this.handleClick} style={styles.addButton}>Add Note</button>
</div>
);
}
}
class NotesList extends Component {
render() {
return (
<div>
{this.props.notes.map(note =>
<div key={note.id} style={styles.note}>
<p>{note.text}</p>
<button onClick={() => { this.props.deleteNote(note) }} style={styles.deleteButton}>x</button>
</div>
)}
</div>
);
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = { notes: [] };
}
async componentDidMount() {
var result = await API.graphql(graphqlOperation(listNotes));
this.setState({ notes: result.data.listNotes.items });
}
deleteNote = async (note) => {
const id = {
id: note.id
};
await API.graphql(graphqlOperation(deleteNote, { input: id }));
this.setState({ notes: this.state.notes.filter(item => item.id !== note.id) });
}
addNote = async (note) => {
var result = await API.graphql(graphqlOperation(createNote, { input: note }));
this.state.notes.push(result.data.createNote);
this.setState({ notes: this.state.notes });
}
render() {
return (
<div style={styles.container}>
<h1>Notes App</h1>
<AddNote addNote={this.addNote} />
<NotesList notes={this.state.notes} deleteNote={this.deleteNote} />
<AmplifySignOut />
</div>
);
}
}
export default withAuthenticator(App);
const styles = {
container: { width: 480, margin: '0 auto', padding: 20 },
form: { display: 'flex', marginBottom: 15 },
input: { flexGrow: 2, border: 'none', backgroundColor: '#ddd', padding: 12, fontSize: 18 },
addButton: { backgroundColor: 'black', color: 'white', outline: 'none', padding: 12, fontSize: 18 },
note: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 22, marginBottom: 15 },
deleteButton: { fontSize: 18, fontWeight: 'bold' }
}
您现在就有了一个运转的应用程序。使用多重验证登录,应用程序现在可以与 API 通信以保存/更新/删除备注。要在本地进行测试,请再次运行 npm start 进行确认。
