【问题标题】:Return error information from API when using Next-auth使用 Next-auth 时从 API 返回错误信息
【发布时间】:2022-02-01 20:50:36
【问题描述】:

是否可以允许 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 }
      }
    }
  })
]

如果有其他帖子与此相关,请告诉我,因为我无法在网上找到它。

【问题讨论】:

    标签: javascript next.js next-auth


    【解决方案1】:

    是的,这应该允许您这样做,尽管在凭据中,将值传递给下一个身份验证时,添加 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 }))
          }
        }
      })
    

    【讨论】:

    • 这似乎奏效了。谢谢!
    猜你喜欢
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    相关资源
    最近更新 更多