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

Node.js调用AWS AppSync查询遇CredentialsProviderError问题求助

问题分析与解决方案

核心错误原因

CredentialsProviderError: Could not load credentials from any providers 表示AWS SDK无法找到有效的IAM凭证,导致无法对AppSync请求进行签名。同时你的代码和Schema存在认证方式混淆的问题,需要先理清需求。


一、先修复凭证问题(若坚持使用IAM认证)

如果你的目标是用IAM身份访问AppSync(对应Schema中的@aws_iam),本地开发时必须提供有效的AWS IAM凭证:

  • 方法1:设置环境变量
    在启动Node.js服务前,在终端执行:

    set AWS_ACCESS_KEY_ID=你的IAM访问密钥ID
    set AWS_SECRET_ACCESS_KEY=你的IAM秘密访问密钥
    # Linux/macOS系统替换为export命令
    
  • 方法2:配置本地凭证文件
    在用户目录下创建~/.aws/credentials文件(Windows路径为C:\Users\<你的用户名>\.aws\credentials),内容如下:

    [default]
    aws_access_key_id = 你的IAM访问密钥ID
    aws_secret_access_key = 你的IAM秘密访问密钥
    region = us-east-1
    
  • 方法3:使用AWS CLI配置
    执行aws configure命令,按提示输入访问密钥、秘密密钥、区域等信息,CLI会自动生成上述凭证文件。

注意:用于认证的IAM用户必须被授予AppSync访问权限,比如附加AmazonAppSyncFullAccess策略,或自定义策略允许appsync:GraphQL动作。


二、修正认证方式混淆(若要使用Cognito用户池认证)

你提到想通过Cognito认证,但当前代码用的是IAM签名方式。Schema中的@aws_cognito_user_pools表示该接口允许Cognito用户池的用户访问,此时不需要IAM签名,而是用Cognito用户的ID Token作为凭证:

修改代码示例:

// 移除IAM签名相关依赖和代码,直接发送带Cognito Token的请求
const handler = async (event) => {
  // 替换为用户登录后获取的真实Cognito ID Token
  const cognitoIdToken = '用户的Cognito ID Token';

  let statusCode = 200;
  let body;

  try {
    const response = await fetch(GRAPHQL_ENDPOINT, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${cognitoIdToken}`
      },
      body: JSON.stringify({ query })
    });
    body = await response.json();
    if (body.errors) statusCode = 400;
  } catch (error) {
    statusCode = 500;
    body = { errors: [{ message: error.message }] };
  }

  return { statusCode, body: JSON.stringify(body) };
};

三、代码中的语法与逻辑错误修复

  1. 模板字符串未闭合:你的query变量最后缺少反引号`,导致语法错误:

    // 修正前
    const query = `query MyQuery {
      listCountrys {
        items {
          countryName
        }
      }
    }
    // 修正后
    const query = `query MyQuery {
      listCountrys {
        items {
          countryName
        }
      }
    }`;
    
  2. Express路由未返回响应:当前路由调用handler()但没有将结果返回给客户端,修改为:

    app.get('^/public/posts/:id', async (req, res, next) => {
      const result = await handler(req);
      res.status(result.statusCode).json(JSON.parse(result.body));
    });
    

内容的提问来源于stack exchange,提问作者Fazle Rabbi Ador

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:35:50