是否可以允许 next-auth 从 API 返回错误并从客户端传递它们?
例如,如果用户的电子邮件或密码不正确,API 会专门返回。在我们的移动应用程序上,这很好用。尽管在网站上,我们使用的是 Next-auth。使用文档中的凭据示例,将返回值更改为对象会很棒。
import CredentialsProvider from "next-auth/providers/credentials"
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
username: { label: "Username", type: "text", placeholder: "jsmith" },
password: { label: "Password", type: "password" }
},
async authorize(credentials, req) {
const user = { id: 1, name: "J Smith", email: "jsmith@example.com" }
if (user) {
// Any object returned will be saved in `user` property of the JWT
return user
} else {
// Return an object that will pass error information through to the client-side.
return { errors: user.errors, status: false }
}
}
})
]
如果有其他帖子与此相关,请告诉我,因为我无法在网上找到它。
最佳答案
是的,这应该允许您这样做,但在凭证中,当将值传递给下一个身份验证时,添加一个 redirect:false
您可以找到文档 here
因此,您的登录方法将如下所示。
signIn('credentials', { redirect: false, username:'username', password: 'password' })
你的代码可以是这样的
import CredentialsProvider from "next-auth/providers/credentials"
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
username: { label: "Username", type: "text", placeholder: "jsmith" },
password: { label: "Password", type: "password" }
},
async authorize(credentials, req) {
const user = { id: 1, name: "J Smith", email: "jsmith@example.com" }
if (user) {
// Any object returned will be saved in `user` property of the JWT
return user
} else {
// Return an object that will pass error information through to the client-side.
throw new Error( JSON.stringify({ errors: user.errors, status: false }))
}
}
})
关于javascript - 使用 Next-auth 时从 API 返回错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70897330/