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

Next.js 14 集成 AWS Amplify v6 遇凭证为空错误求助

Next.js 14 + AWS Amplify v6 调用REST API报NoCredentials错误解决方法

问题描述

已完成amplify init初始化、REST API创建及所有依赖安装,在Next.js 14的Root Layout客户端组件中按文档配置Amplify后,调用POST接口时出现以下错误:

POST call failed: NoCredentials: Credentials should not be empty.

用户配置及调用代码如下:

'use client'

import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'] })
import { Amplify } from 'aws-amplify';
import config from '../amplifyconfiguration.json';

Amplify.configure(config, { ssr: true });
import { post } from 'aws-amplify/api';


async function postTodo() {
  
  try {
    const restOperation = post({
      apiName: "todoApi",
      path: '/todo',
      options: {
        body: {
          message: 'Mow the lawn'
        }
      }
    });
    await restOperation.response;
    console.log('POST call succeeded');
    // console.log(response);
  } catch (e) {
    console.log('POST call failed: ', e);
  }
}

postTodo()

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
          {children}
      </body>
    </html>
  )
}

解决步骤

  • 检查Amplify配置的认证凭证
    打开amplifyconfiguration.json,确认对应REST API的认证配置完整:

    • 若使用API Key认证,需确保authorizationType为API_KEY且存在apiKey字段;
    • 若使用IAM认证,需确保前端能获取合法IAM凭证(开发环境可通过amplify add auth配置Cognito用户池,或临时使用AWS credentials)。
      示例API Key认证配置片段:
    "api": {
      "rest": {
        "todoApi": {
          "endpoint": "https://xxx.execute-api.region.amazonaws.com/dev",
          "region": "us-east-1",
          "authorizationType": "API_KEY",
          "apiKey": "your-valid-api-key"
        }
      }
    }
    
  • 修正Amplify初始化的SSR配置
    Root Layout是客户端组件(标注'use client'),无需开启SSR模式,移除ssr: true配置:

    Amplify.configure(config); // 移除{ ssr: true }参数
    
  • 调整API调用时机
    当前代码在模块加载阶段直接执行postTodo(),此时Amplify可能未完成初始化。将API调用放到React生命周期钩子中:

    // 导入useEffect
    import { useEffect } from 'react';
    
    // 在Layout组件内添加useEffect
    export default function RootLayout({ children }) {
      useEffect(() => {
        postTodo(); // 组件挂载后再调用API
      }, []);
    
      // ... 其余代码不变
    }
    
  • 验证API Gateway的CORS配置
    登录AWS控制台进入API Gateway,找到todoApi,检查CORS配置是否允许当前应用域名的请求(开发环境可临时设置Access-Control-Allow-Origin为*测试)。

  • 拉取最新Amplify配置
    执行amplify pull命令,确保amplifyconfiguration.json是最新生成的配置文件,避免配置缺失或过期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 12:32:15