javascript - 使用 Next-auth 时从 API 返回错误信息

标签 javascript next.js next-auth

是否可以允许 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/

相关文章:

javascript - .each() 表现得很奇怪

javascript - 使用扩展运算符创建数组

reactjs - 图像路径很奇怪,部署 Next.js 应用程序后我看不到任何图像

reactjs - Next JS 导出到静态 HTML 总是在刷新时重定向到主页 "/"

JavaScript - 无法解决此问题 'warning: promise was created in a handler'

javascript - 动态检查单选按钮的值(重构题)

reactjs - @urql/exchange-auth 不在 header 中发送 token

reactjs - 如何在中间件中获取 nextAuth session

next.js - 如何在 next-auth 中保护多个 Next.js API 路由

next.js - NextAuth 登录将参数传递给回调