我有一个自定义登录页面,它在提交表单时调用signIn()
函数。
我只使用"凭据">提供者。
服务器端,我只是想抛出一个错误,所以我可以在前端处理它。这似乎很容易。
我继续得到一个错误的状态:Error: HTTP GET is not supported for /api/auth/login?callbackUrl=http://localhost:4000/login
http://localhost:4000/api/auth/login?callbackUrl=http://localhost:4000/login
下面是我的代码:页面/login.js(只提供相关代码。)
<form
method="post"
onSubmit={() =>
signIn("credentials", {
email: "test",
password: "test",
})
}
>
<label>
Username
<input type="email" />
</label>
<label>
Password
<input name="password" type="password" />
</label>
<button type="submit">Sign In</button>
</form>
页面/api/认证/[…nextauth.js]
import NextAuth from "next-auth";
import Providers from "next-auth/providers";
const options = {
site: process.env.NEXTAUTH_URL,
providers: [
Providers.Credentials({
id: "chatter",
name: "Credentials",
type: "credentials",
credentials: {
email: { label: "Email", type: "email", placeholder: "email@domain.com" },
password: { label: "Password", type: "password" },
},
authorize: async credentials => {
console.log("credentials:", credentials);
throw new Error("error message"); // Redirect to error page
},
}),
],
pages: {
signIn: "login",
newUser: null,
},
};
export default (req, res) => NextAuth(req, res, options);
你可以这样写:
signIn("credentials", {
redirect: false,
email: "test",
password: "test",
})
.then((error) => console.log(error))
.catch((error) => console.log(error));
这个答案帮助我解决了我的问题:
https://stackoverflow.com/a/70760933/11113465
如果您将redirect
设置为false,signIn
方法将返回以下格式的承诺:
{
error: string | undefined // Error code based on the type of error
status: number // HTTP status code
ok: boolean // `true` if the signin was successful
url: string | null // `null` if there was an error
}
然后你可以处理你喜欢的错误:
const { error } = await signIn('credentials', {
phone_number: phoneNumber,
verification_code: code.toString(),
redirect: false,
});
if (error) {
// handle error
} else {
router.push(callbackUrl);
}
是否在pages/api/auth中检查[…nextauth].js ?
我有同样的问题,但我可以修复[…nextauth].js移动'pages/api'到'pages/api/auth'.