首页 > 解决方案 > http://localhost:3000/api/user/[object%20Object] 处的无效 json 响应正文原因:意外的令牌 < 在 JSON 中的位置 0

问题描述

我正在使用此示例使用 Nextjs 创建一个简单的身份验证https://github.com/vvo/next-iron-session/tree/master/examples/next.js

但是我没有从 Github 获取用户 JSON 对象(如示例那样),而是尝试从我有一些用户的 mongodb 数据库中进行操作。

我在我的login.js文件上做了这个:

import fetchJson from "../../lib/fetchJson";
import withSession from "../../lib/session";
import { withIronSession } from "next-iron-session";
import { connectToDatabase } from "../../util/mongodb";

export default withSession(async (req, res) => {
  const { db } = await connectToDatabase();

  const { username } = await req.body;
  
  const foundUser = await db.collection("users").findOne({"userName": username});

  console.log(foundUser) // <--- this returns the user object on console just fine
  
  
  const url = `http://localhost:3000/api/user/${foundUser}`;

  try {

    const { userName, email } = await fetchJson(url);
    const user = { isLoggedIn: true, userName, email }
    
    
    req.session.set("user", user);
    await req.session.save();
    res.json(user);
  } catch (error) {
    const { response: fetchResponse } = error;
    res.status(fetchResponse?.status || 500).json(error.data);
    
  }
});

我的/api/user.js文件中有这段代码:

import withSession from "../../lib/session";
import { connectToDatabase } from "../../util/mongodb";

export default withSession(async (req, res) => {
  const user = req.session.get("user");

  
  if (user) {
    
    const { db } = await connectToDatabase();
    
    const foundUser = await db.collection("users").findOne({"userName": user.userName, "email": user.email});

    console.log("useri pi te user.js " + foundUser)
    
    // in a real world application you might read the user id from the session and then do a database request
    // to get more information on the user if needed

res.json({
      
      isLoggedIn: true,
      ...user,
    });
  } else {
    res.json({
      isLoggedIn: false,
    });
  }
});

但是我得到“在 http://localhost:3000/api/user/[object%20Object] 原因的无效 json 响应正文:意外的令牌 < 在 JSON 中的位置 0”错误,即使我只是在控制台中打印了用户对象美好的。

在此处输入图像描述

任何帮助,将不胜感激!

标签: jsonreactjsexpressauthenticationnext.js

解决方案


推荐阅读