You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextAuth登录报错:Unexpected token < in JSON at position 0 求助

解决NextAuth登录时"Unexpected token < in JSON at position 0"错误

这个错误的核心原因是代码预期接收JSON响应,但实际收到了HTML内容(比如404错误页、服务器错误页的HTML,开头字符为<,导致JSON解析失败)。结合你的代码,按以下步骤排查修复:

1. 检查/api/login接口的响应

你的authorize方法调用了http://localhost:3000/api/login,这个接口大概率是问题源头:

  • 直接用Postman或浏览器开发者工具的Network面板,手动请求该接口并传入用户名密码,查看返回内容是JSON还是HTML。
  • 如果返回HTML(比如404页面),说明接口不存在或配置错误,先修复它——确保无论成功/失败都返回JSON格式(比如失败时返回{"error": "用户名或密码错误"})。

2. 给fetch请求添加错误处理

当前代码仅判断了res.ok,但如果接口返回非JSON内容(比如错误页HTML),res.json()会直接抛出错误。修改authorize方法,增加异常捕获和响应类型检查:

async authorize(credentials, req) {
  try {
    const res = await fetch("http://localhost:3000/api/login", {
        method: 'POST',
        body: JSON.stringify(credentials),
        headers: { "Content-Type": "application/json" }
    })

    // 先验证响应是否为JSON类型
    const contentType = res.headers.get('content-type')
    if (!contentType || !contentType.includes('application/json')) {
      console.error('Login API返回非JSON内容:', await res.text())
      return null
    }

    const user = await res.json()
    if (res.ok && user) {
        return user
    }
  } catch (err) {
    console.error('登录请求出错:', err)
  }
  return null
}

3. 修正NEXTAUTH_URL配置

你当前的NEXTAUTH_URL设置为http://localhost:3000/api/auth,这是错误的。正确配置应为应用根URL:

NEXTAUTH_URL=http://localhost:3000

NextAuth会自动处理/api/auth路径,无需在配置中追加。

4. 确认signIn调用的正确性

尝试明确指定provider,避免潜在的匹配问题:

<Button color="primary" variant="flat" className="text-base" onClick={() => signIn('credentials')}>
  SignIn
</Button>

完成以上步骤后,重启应用测试登录功能,即可解决该JSON解析错误。

内容的提问来源于stack exchange,提问作者Arnz3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 18:40:18