【发布时间】:2021-04-02 07:35:06
【问题描述】:
此代码的工作方式应该可以正常工作,但是在第五次 GET 请求之后,它会在后端执行应执行的操作(将数据存储在 db 中),但它没有在服务器上记录任何内容,也没有任何更改在前端(reactjs)
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const User = require('./login').User;
mongoose.connect('mongodb://localhost:27017/animationsdb');
router.get('/', async(req, res) => {
await User.findOne({ username: req.query.username }, (err, result) => {
if (result) {
// when user goes to his profile we send him the list of animations he liked
// list is stored in array at db, field likedAnimations
res.send({ animationList: result.likedAnimations });
console.log("Lajkovane animacije:", result.likedAnimations);
} else {
console.log("no result found");
res.sendStatus(404)
}
});
});
router.put('/', async(req, res) => {
console.log("username:", req.body.username);
console.log("link:", req.body.link);
// if animation is already liked, then dislike it
// if it's not liked, then store it in db
const user = await User.findOne({ username: req.body.username });
if (user.likedAnimations.indexOf(req.body.link) === -1) {
user.likedAnimations.push(req.body.link);
} else {
user.likedAnimations = arrayRemove(user.likedAnimations, user.likedAnimations[user.likedAnimations.indexOf(req.body.link)]);
}
user.save();
});
function arrayRemove(arr, value) {
return arr.filter((item) => {
return item != value;
});
}
module.exports = router;
对于前五个请求,我得到以下输出:
Liked animations: ["/animations/animated-button.html"]
GET /animation-list/?username=marko 200 5.152 ms - 54
Liked animations: ["/animations/animated-button.html"]
GET /animation-list/?username=marko 304 3.915 ms - -
在刷新页面之前,我在服务器控制台上没有任何输出,前端也没有任何变化,即使数据库操作仍然有效并且数据已保存。
【问题讨论】:
-
此请求处理程序有两个根本不发送响应的代码路径。 1) 如果
User.findOne()失败并拒绝或 2) 如果result是假的(没有找到)。在这两种情况下,您都应该发送适当的响应。每当发生可疑的事情时,我要做的第一件事就是调查我的错误处理,看看是否发生了我没有正确处理的事情。此外,您可以在服务器上记录所有可能的代码路径,并查看您是否收到了请求,如果收到了,它会采用什么路径。你可以通过更多的日志记录来解决这个问题。 -
打开 Chrome 调试器并查看网络选项卡,并查看当您发出这些似乎没有显示任何内容的客户端请求时服务器返回给您的确切内容。
-
另外,该代码不会将任何内容保存到数据库中?
-
@ChrisG 它触发保存的代码
-
您发布的代码仅包含一个读取 DB (User.findOne) 的查询,没有向其写入任何内容。
标签: javascript node.js reactjs typescript express