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

AWS Amplify调用API报错NoCredentials: Credentials should not be empty求助

解决AWS Amplify调用API时的NoCredentials错误

核心原因及修复方案

1. 检查API Gateway的访问权限

  • 若API无需认证:登录AWS控制台进入API Gateway,找到目标API,在资源页选择对应路径,点击方法请求,将授权类型设为NONE,重新部署API。
  • 若API需要认证:确保已通过Amplify配置用户池/身份池,前端需先完成用户登录以获取有效凭证。

2. 验证amplifyconfiguration.json配置

确认配置文件中API和Auth字段正确:

  • API部分需保证apiName、endpoint、region与控制台一致
  • 启用Auth时,身份池(Identity Pool)配置必须正确,Amplify会自动从中获取临时访问凭证

3. 添加认证逻辑(针对需认证的API)

若API要求认证,需在前端实现登录流程,示例代码修改如下:

// App.js中导入Auth模块
import { get } from "aws-amplify/api";
import { useState } from "react";
import { signIn } from "aws-amplify/auth";

// ... 原有代码

// 新增登录函数
async function handleLogin() {
  try {
    await signIn({ username: "你的用户名", password: "你的密码" });
    console.log("登录成功");
  } catch (error) {
    console.error("登录失败", error);
  }
}

// 组件中添加登录按钮
return (
  <div className="App">
    <button onClick={handleLogin}>登录</button>
    {/* 原有UI代码 */}
  </div>
);

4. 本地开发使用Amplify模拟服务

本地调试时可绕过认证,启动模拟API:

  • 执行命令 amplify mock api 启动本地模拟服务,此时API允许未认证访问
  • 确保amplifyconfiguration.json是通过amplify pull生成的本地模拟配置

5. 确认Amplify项目与AWS账户关联一致性

  • 执行 amplify status 查看当前Amplify项目关联的AWS环境和账户
  • 若与本地aws configure账户不一致,执行amplify configure重新关联正确账户

代码优化建议

原getCustomer函数中,需解析HTTP响应的JSON数据才能拿到业务内容:

async function getCustomer(e) {
  let customerId = e.input;
  try {
    const restOperation = get({
      apiName: myAPI,
      path: path + "/" + customerId,
    });

    const response = await restOperation.response;
    const customerData = await response.json(); // 解析响应JSON
    console.log(customerData);
    let newCustomers = [...customers];
    newCustomers.push(customerData); // 使用解析后的数据更新状态
    setCustomers(newCustomers);
  } catch (error) {
    console.log("GET call failed: ", error);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:05:28