如何在Next/React前端正确实例化AWS Rekognition客户端?
解决AWS SDK v3中Rekognition客户端实例化的类型错误
你遇到的类型错误核心原因是:fromCognitoIdentityPool的参数对象中,客户端属性的正确名称是cognitoIdentityClient,而非你代码里的client,TypeScript检测到未知属性client因此抛出类型不匹配错误。
以下是修正后的完整代码,同时包含前端环境适配和性能优化:
import { RekognitionClient, DetectModerationLabelsCommand, } from '@aws-sdk/client-rekognition'; import { fromCognitoIdentityPool } from '@aws-sdk/credential-providers'; import { CognitoIdentityClient } from '@aws-sdk/client-cognito-identity'; const AWS_REGION = process.env.NEXT_PUBLIC_AWS_REGION!; const AWS_IDENTITY_POOL_ID = process.env.NEXT_PUBLIC_COGNITO_IDENTITY_POOL_ID!; // 复用Rekognition客户端实例,避免每次调用函数重复初始化 const rekognitionClient = new RekognitionClient({ region: AWS_REGION, credentials: fromCognitoIdentityPool({ identityPoolId: AWS_IDENTITY_POOL_ID, // 修正属性名为 cognitoIdentityClient cognitoIdentityClient: new CognitoIdentityClient({ region: AWS_REGION }), // 可选:若需手动指定登录用户身份,取消注释并替换为你的用户池ID和用户JWT令牌 // login: { // [`cognito-idp.${AWS_REGION}.amazonaws.com/${YOUR_USER_POOL_ID}`]: USER_JWT_TOKEN // } }), }); const moderateImage = async (imagePath: string) => { // 前端环境下替代Node.js Buffer的Base64转字节数组方案 const base64Image = imagePath.split(';base64,').pop()!; const binaryString = atob(base64Image); const bytes = new Uint8Array(binaryString.length); for (let i = 0; i < binaryString.length; i++) { bytes[i] = binaryString.charCodeAt(i); } const params = { Image: { Bytes: bytes, }, MinConfidence: 70, }; const command = new DetectModerationLabelsCommand(params); const response = await rekognitionClient.send(command); return response; }; export default moderateImage;
补充说明
- 客户端复用:将RekognitionClient实例提取到函数外部,避免每次调用图片审核函数都重复创建客户端,提升性能。
- 前端兼容性:使用
atob和Uint8Array替代Node.js的Buffer,适配浏览器/Next.js前端环境的运行需求。 - 身份关联:若身份池已关联Cognito用户池且用户已登录,无需手动配置
login参数,身份池会自动关联当前用户身份;若需手动传入用户凭证,可启用注释中的login配置。
内容的提问来源于stack exchange,提问作者Richard Horrocks
相关产品推荐
相关产品推荐

