NextAuth.js Credentials Provider登录报错:fetch失败排查
NextAuth.js Credentials Provider登录时fetch失败错误排查
登录时触发以下错误:
[auth][error] CallbackRouteError: Read more at https://errors.authjs.dev#callbackrouteerror [auth][cause]: TypeError: fetch failed
相关代码
app/lib/auth.js
import NextAuth from "next-auth"; import Credentials from "next-auth/providers/credentials"; const URL = process.env.NEXT_PUBLIC_API_URL; const Token = process.env.NEXT_PUBLIC_TOKEN; export const { handlers, signIn, signOut, auth } = NextAuth({ providers: [ Credentials({ credentials: { email: { label: "Email", type: "email" }, password: { label: "Password", type: "password" }, }, authorize: async (credentials) => { const { email, password } = credentials; console.log(email, password); console.log(`${URL}auth/jwt/create/`); const body = JSON.stringify({ email, password }); const res = await fetch(`${URL}auth/jwt/create/`, { method: "POST", headers: { "Content-Type": "application/json", }, body, }); if (!res.ok) { throw new Error("Failed to sign in"); } else { const data = await res.json(); return data; } }, }), ], });
登录组件
import { signIn } from "@/app/lib/auth"; import { executeAction } from "../lib/executeAction"; function Page() { return ( <main> <form action={async (formData) => { "use server"; await executeAction({ actionFn: async () => { await signIn("credentials", formData); }, }); }} > <h1>Sign in</h1> <input name="email" type="email" required /> <input name="password" type="password" required /> <button type="submit">Sign in</button> </form> </main> ); } export default Page;
app/api/auth/[...nextauth]/route.js
import { handlers } from "@/app/lib/auth"; export const { GET, POST } = handlers;
已完成的排查
- .env.local文件中
NEXT_PUBLIC_API_URL和NEXT_PUBLIC_TOKEN配置无误 - 后端URL及
auth/jwt/create/端点路径正确 - 后端服务运行正常,可通过Postman/cURL正常访问
疑问
目前authorize方法内的fetch请求仍失败,请问可能的原因是什么?该如何解决?
内容的提问来源于stack exchange,提问作者Lucas
相关产品推荐
相关产品推荐

