在我的应用程序的后端,我试图将 jsonwebtoken 的 id 字段保存到我以用户身份登录后创建的项目中。我目前可以控制台记录 JWT 的信息,但由于某种原因,它不允许我将 id 字段分配给我的项目。
//API endpoint for posting items
app.post("/postItem", async (req: Request, res: Response) => {
console.log(req.body);
const { token } = req.cookies;
jwt.verify(token, secret, {}, async (err: Error, info: Response) => {
if (err) throw err;
console.log(info);
const newItem = new Item({
name: req.body.name,
price: req.body.price,
category: req.body.category,
});
try {
const createdItem = await newItem.save();
res.json(createdItem);
} catch (e) {
res.status(400).json(e);
}
});
});
我尝试执行 info.id 但它说 id 不存在,即使我能够通过控制台记录 id
//console.log(info) prints out { username: '1', id: '6599df386a8a03974c315e01', iat: 1704845251 } in my terminal
const newItem = new Item({
name: req.body.name,
price: req.body.price,
category: req.body.category,
author: info.id, //where the error is
});
您可以尝试使用像 info?.id 这样的可选链接,也可以删除验证函数第三个参数空对象。