NextAuth:如何在不重定向的情况下返回自定义错误

编程入门 行业动态 更新时间:2024-10-03 06:33:47

NextAuth:如何在不重定向的情况下返回<a href=https://www.elefans.com/category/jswz/34/1771438.html style=自定义错误"/>

NextAuth:如何在不重定向的情况下返回自定义错误

我一直在考虑使用用户名和密码凭据实现 NextAuth,但没有找到将自定义错误返回到客户端的方法。看来我只能从授权方法返回 200 ok 或重定向到错误页面,然后您可以在查询字符串中添加自定义错误。然而,这对于我的情况来说不是一个正确的解决方案,因为我需要客户端仅从 sigIn 调用接收自定义错误代码或消息。

如何返回自定义错误,例如

“电子邮件地址无效”

“帐户被封锁”

“密码无效”

或者需要任何其他定制吗?

谢谢

回答如下:

如果您的应用程序没有使用 next-auth 页面并使用自定义页面,则在使用

signIn
功能时,必须在登录页面中将重定向设置为 false,以下是一个示例:

// login.jsx

const [datas, setDatas] = useState({ credential: '', password: '' })

const handleSubmit = async e => {
    e.preventDefault()
    try {
      // siging in
      const res = await signIn('credentials', {
        credential: datas.credential, // can be changed to `email` or `username` or anything else
        password: datas.password,
        redirect: false // this is important
      })
      if (res?.status == 200) {
        push('/')
      } else {
        throw new Error(res?.error)
      }
    } catch (error) {
      console.log(error.message) // error in the provider
    }
}

并且在提供程序中,您必须抛出您希望看到的错误

// [...nextauth].js

providers: [
    // credentials provider
    CredentialsProvider({
        type: 'credentials',
        credentials: {},

        // authorization function
        async authorize(credentials, req) {
            const { credential, password } = credentials

            // admin profile
            let data = { credential : 'test', password: 'abcd' } // replace this

            if (!data) throw new Error('no user found')
            if (data.credential != credential) throw new Error('invalid credentials')

            // comparing the password
            const compared = data.password != password // replace this

            // checking if the password was correct
            if (!compared) throw new Error('invalid credentials')

            return data // success
        }
    })
],

如果我有错别字,请小心

更多推荐

NextAuth:如何在不重定向的情况下返回自定义错误

本文发布于:2024-05-31 06:55:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771391.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   不重   情况下   错误   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!