我正在尝试将我的 Next.js 应用程序 (v14) 与 Amplify (v6) 连接。 我已经设置了 amplify,运行 amplify init 并创建其余 api,并安装所有依赖项。
然后,在我的 Layout 组件中配置 Amplify 时,我遇到了一些麻烦。根据 Amplify 文档,我应该导入 Amplify 并在 Layout.tsx 中按如下方式配置它:
'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';
所以,这样,我的文件(包含其余代码)如下:
'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>
)
}
浏览器加载页面时,会记录消息:“POST 调用失败:NoCredentials:凭据不应为空。”
我非常感谢您的支持,因为我已经尝试解决这个问题一个多星期了,但没有成功。
您必须在 options 中添加 headers :
options: {
body: {
message: 'Mow the lawn'
},
headers: {
Authorization: "test",
}
}