我是node.js的新手,我只是想了解这些东西的异步性质。 好的,这是一个非常简单的表单提交。模型如下所示: -
var mongoose=require('mongoose');
var Schema=mongoose.Schema;
var PostSchema=new Schema({
title:{type:String,required:true},
post:String,
});
var PostModel=mongoose.model('blogpost',PostSchema);
module.exports=PostModel;
然后路由处理程序如下: -
app.post("/submitpost",function(req,res){
var title=req.body.title;
var post=req.body.post;
var thepost=new PostModel({title:title,post:post});
thepost.save(function(err,data){
if(err)throw err;
console.log(data);
})
console.log("title is "+title);
console.log("post is "+post);
res.send("saved");
});
现在假设验证在" thepost.save(回调)" ,我想显示一个错误页面,而不是"已保存" 。我该怎么做?
答案 0 :(得分:1)
只需将响应的呈现移动到回调中:
app.post("/submitpost",function(req,res){
var title=req.body.title;
var post=req.body.post;
var thepost=new PostModel({title:title,post:post});
thepost.save(function(err,data){
if(err) {
res.render('errorPage');
} else {
console.log(data);
console.log("title is "+title);
console.log("post is "+post);
res.send("saved");
}
})
});