You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过Amplify调用Lambda REST API获取Cognito组用户列表出现CORS错误求助

问题根因

你遇到的CORS报错本质是预检OPTIONS请求未返回200状态,核心有4个错误点:

  1. 你给/users路径的ANY方法绑定了Cognito授权器,预检OPTIONS请求不会携带Authorization请求头,会直接被授权器拦截返回401,导致预检不通过
  2. Lambda返回的CORS头存在冲突:Access-Control-Allow-Origin: *和Access-Control-Allow-Credentials: true不能同时使用,浏览器会直接拦截这种不符合规范的响应
  3. 你手动在API Gateway修改的配置,后续执行amplify push时会被Amplify的默认配置覆盖,无法生效
  4. Lambda代码中直接从event.groupName取查询参数,实际API Gateway传递的查询参数存放在event.queryStringParameters对象下,取值错误会导致Lambda抛出异常返回500,也会触发CORS报错

解决方案

1. 修复Lambda代码

修改后的Lambda代码如下:

const AWS = require('aws-sdk');
const cognito = new AWS.CognitoIdentityServiceProvider({region:"eu-central-1"});

exports.handler = async (event) => {
    // 正确取查询参数
    const groupName = event.queryStringParameters?.groupName
    if (!groupName) {
        return {
            statusCode: 400,
            headers:{
                // 明确指定允许的源,不要用*
                "Access-Control-Allow-Origin": event.headers?.origin || "http://localhost:3000",
                "Access-Control-Allow-Headers":"Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent",
                "Access-Control-Allow-Methods": "GET,OPTIONS",
                "Access-Control-Allow-Credentials": true
            },
            body: JSON.stringify({msg: "缺少groupName参数"})
        }
    }
    const params = {
        GroupName: groupName, 
        UserPoolId: 'eu-central-1_xqIZx0wkT', 
    };
    try {
        const cognitoResponse = await cognito.listUsersInGroup(params).promise()
        return {
            statusCode:200,
            headers:{
                "Access-Control-Allow-Origin": event.headers?.origin || "http://localhost:3000",
                "Access-Control-Allow-Headers":"Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent",
                "Access-Control-Allow-Methods": "GET,OPTIONS",
                "Access-Control-Allow-Credentials": true
            },
            body: JSON.stringify(cognitoResponse),
        };
    } catch (e) {
        return {
            statusCode: 500,
            headers:{
                "Access-Control-Allow-Origin": event.headers?.origin || "http://localhost:3000",
                "Access-Control-Allow-Headers":"Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent",
                "Access-Control-Allow-Methods": "GET,OPTIONS",
                "Access-Control-Allow-Credentials": true
            },
            body: JSON.stringify({msg: "查询用户组失败", error: e.message})
        }
    }
};

2. 修复API Gateway的OPTIONS方法配置

  • 进入AWS控制台API Gateway页面,找到你创建的apilistusersAPI
  • 在资源列表中找到/users路径下的OPTIONS方法,如果不存在则点击操作->启用CORS,按提示配置允许的源、请求头、请求方法,确认后会自动创建OPTIONS方法
  • 点击OPTIONS方法的方法请求,将授权器设置为无,保存修改
  • 点击操作->部署API,选择你对应的dev阶段,让配置生效

3. 用Amplify托管CORS配置避免被覆盖

打开项目中amplify/backend/api/apilistusers/cli-inputs.json文件,添加CORS相关配置,下次执行amplify push时就不会覆盖你的配置:

{
  "cors": {
    "allowOrigins": ["http://localhost:3000"],
    "allowHeaders": ["Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent"],
    "allowMethods": ["GET", "OPTIONS"],
    "allowCredentials": true
  }
}

修改完成后执行amplify push部署即可。

内容的提问来源于stack exchange,提问作者julienlaurent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 12:54:05