我正在尝试对我的应用程序执行editpost函数,但是我不断收到一条错误消息,提示“ body is undefined”
ReferenceError:主体未定义 在EditPost(C:\ server \ controllers \ posts.js:161:36)
我包括了控制器,组件和html。
对于控制器
editPost(req, res) {
console.log(body);
const Schema = Joi.object().keys({
post: Joi.string().required(),
id: Joi.string().optional()
});
const { error } = Joi.validate(body, Schema);
if (error && error.details) {
return res.status(httpStatus.BAD_REQUEST).json({
msg: error.details
});
}
const body = {
post: req.body.post,
created: new Date()
};
Post.findOneAndUpdate({ _id: req.body.id }, body, { new: true })
.then(post => {
res
.status(httpStatus.OK)
.json({ message: "Post updated successfully", post });
})
.catch(err => {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
message: err
});
});
}
帖子部分
SubmitEditedPost() {
console.log(this.editForm.value);
const body = {
id: this.postValue._id,
post: this.editForm.value.editedPost
}
this.postService.editPost(body).subscribe(data => {
console.log(data)
this.socket.emit('refresh', {})
}, err => console.log(err))
M.Modal.getInstance(this.modalElement).close();
this.editForm.reset();
}
和HTML
<div class="container">
<div id="modal" class="modal">
<div class="modal-content">
<h4>
Edit Post
<button class="button"(click)="CloseModal()"> Close </button>
</h4>
<p *ngIf="postValue"> {{postValue.post}} </p>
<form [formGroup]="editForm" novalidate>
<textarea formControlName="editedPost" class="materialize-textarea"></textarea>
<div class="modal-footer">
<button class="secondary-content deleteBtn btn">Delete</button>
<button class="btn" (click)="SubmitEditPost()" >Save</button>
</div>
</form>
</div>
</div>
</div>
答案 0 :(得分:0)
删除代码中的
之前使用IReadOnlySessionState
。因为它在定义变量
或
在使用前定义IRequiresSessionState
变量,因此,应将以下代码移到顶部。
console.log(body);
答案 1 :(得分:0)
在editPost
函数顶部定义主体
editPost(req, res) {
const body = {
post: req.body.post,
created: new Date()
};
console.log(body);
const Schema = Joi.object().keys({
post: Joi.string().required(),
id: Joi.string().optional()
});
const { error } = Joi.validate(body, Schema);
if (error && error.details) {
return res.status(httpStatus.BAD_REQUEST).json({
msg: error.details
});
}
Post.findOneAndUpdate({ _id: req.body.id }, body, { new: true })
.then(post => {
res
.status(httpStatus.OK)
.json({ message: "Post updated successfully", post });
})
.catch(err => {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
message: err
});
});
}