【发布时间】:2020-08-23 21:52:16
【问题描述】:
我正在开发一个小型计时器应用程序,但遇到了 router.post() 必须为 MongoDB 赋值的部分。关键是每次用户按下暂停按钮时都会创建 MongoDB 中的数据,但没有来自 Schema Module 的值...只有 ID、createdAt 和 updatedAt 来自 Module 类的时间戳。我尝试通过简单地添加 console.log() 来调试 router.post() :
router.post('/savetasks', function(req, res) {
console.log(req.body);
// my logic.....
}
结果是一个空数组:(现在我假设问题可能出在我的模块配置中......或者订阅/流式传输数据的方式。
router.post() 方法
router.post('/savetasks', async (req, res) => {
console.log(req.body);
const { startTime, endTime, elapsedTime } = req.body;
const newTime = new Time({startTime, endTime, elapsedTime});
await newTime.save();
const token = jwt.sign({ _id: newTime._id}, 'secretkey');
res.status(200).json({token});
});
Time.js 类
const { Schema, model } = require('mongoose');
const timeSchema = new Schema({
startTime: String,
endTime: String,
elapsedTime: String
}, {
timestamps: true
});
module.exports = model('Time', timeSchema);
HttpClient
postTasks(times) {
return this.httpClient.post(this.URL + '/savetasks', times);
}
我订阅的方式...它是从 pauseTimer() 方法中调用的
pauseTimer() {
clearInterval(this.interval);
this.endTime = new Date();
console.log(this.endTime);
this.elapsedTime = this.endTime - this.startTime
console.log(this.elapsedTime);
this.tasksService.postTasks(this.time)
.subscribe(
res => {
this.time = res;
//this.elapsed = res;
console.log(this.time);
},
err => console.log(err)
);
}
【问题讨论】:
-
console.log 打印是什么?
-
Kunal Mukherjee 对于后端,它是一个空数组。而对于前端只有令牌 {token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1Z…1NzV9.rItkiR4A2OC5OlW4uOlWCzRoNOlzKdyQGhyRoe7UmwM"}
-
我认为问题在于发布数据,将此行更改为 -
this.tasksService.postTasks({ startTime: this.startTime, endTime: this.endTime, elapsedTime: this.endTime - this.startTime }) -
Kunal Mukherjee 绝对是个问题,现在可以了 :)))) 非常感谢!!!
-
@KunalMukherjee:为此创建一个 OP 可以接受的答案 :)