json - 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”错误,即使我只是在控制台中打印了用户对象美好的。
任何帮助,将不胜感激!
解决方案
推荐阅读
- discord - 如何通过命令启用慢模式?
- python-3.x - 如何在python中将类型结果转换为字符串?
- google-chrome-extension - Chrome 扩展 - 在单击扩展图标上设置剪贴板
- vmware - VM 工作站暂停物理主机状态以关闭
- javascript - 单击 function()、querySelectorAll、getElementByClassName 和 getElementById,尝试所有变体
- python - dynamics 365 API 9.1 将联系人与机会相关联
- java - 比较 java unittests 中的两个 hasmaps 列表
- image - 当 tkinter.PhotoImage 使用 png 文件时,为什么要使用枕头?
- c++ - Rcpp 通过 NumericVector 选择/子集 NumericMatrix 列
- docker - 如何检查 docker 容器中是否正在运行任何应用程序?