代码示例:
import { withAuthenticator } from 'aws-amplify-react'; import Amplify from 'aws-amplify'; import awsconfig from './aws-exports';
Amplify.configure(awsconfig); const App = () => { // ... }; export default withAuthenticator(App);
在 AWS API Gateway 中创建一个 REST API,并根据需要添加资源、方法和集成。
在 React 应用中使用 AWS SDK for JavaScript with Cognito Identity SDK 和 Amazon API Gateway SDK(例如,@aws-sdk/client-apigatewayv2)进行 API 调用。
代码示例:
import { CognitoIdentityClient } from '@aws-sdk/client-cognito-identity'; import { fromCognitoIdentityPool } from '@aws-sdk/credential-provider-cognito-identity'; import { ApiGatewayManagementApiClient } from '@aws-sdk/client-apigatewayv2';
const client = new ApiGatewayManagementApiClient({ region: 'REGION', endpoint: 'wss://API_GATEWAY_ID.execute-api.REGION.amazonaws.com/STAGE', credentials: fromCognitoIdentityPool({ client: new CognitoIdentityClient({ region: 'REGION' }), identityPoolId: 'IDENTITY_POOL_ID', }), });
const sendMessage = async (message) => { await client.postToConnection({ ConnectionId: 'CONNECTION_ID', Data: JSON.stringify({ type: 'message', data: message }), }); };
代码示例:
import { API } from 'aws-amplify';
const { data: { Items: connections } } = await API.get('API_NAME', '/CONNECTIONS'); const connectionId = connections[0].connectionId;
const sendMessage = async (message) => { await API.post('API_NAME', '/SEND_MESSAGE',
上一篇:AWSAPIGateway如何创建create_api_key,需要哪些权限?
下一篇:AWSAPIGateway如何将4XX和5XX错误记录在Cloudwatch中?例如,在Cloudwatch中查找状态代码413,“请求实体太大错误如何记录?