我在路由里面这样写:
app.get('/product/:id',Product.detail);
Product.detail是这样的:
exports.detail = function (req,res,next){
var id = new mongoose.Schema.ObjectId(req.params.id).path;
logger.info(id);
ProductDB.findById(id,function(err,product){
if(err){
logger.error(err);
return next(err);
}
CommentDB
.find({product: id})
.populate('from','name')
.populate('reply.from reply.to','name')
.exec(function(err,comments){
if(err){
logger.error(err);
return next(err);
}
var _product = _.extend({},product);
var _comments = _.extend({},comments);
return res.render('detail',{
title: _product.title,
product: _product,
comments: _comments
});
});
});
};
之后起服务,页面正常
http://localhost:3000/product/56335734f8e5b62182dc0d35
可是发现多发了一次请求,且这次请求拿不到params.id,导致momgoose会报CastError,如下undefined:
GET /product/56335734f8e5b62182dc0d35 304
zhishifan started on port: 3000
GET /libs/jquery/dist/jquery.min.js 304
GET /libs/bootstrap/dist/css/bootstrap.min.css 304
GET /libs/bootstrap/dist/js/bootstrap.min.js 304
GET /product/undefined 304
zhishifan started on port: 3000
GET /js/comment.js 304
GET /libs/jquery/dist/jquery.min.map 304
实在没想通这次请求从哪里出来的,路由里也没有重复的定义,求指导。
另,如果只对请求做最简单的render,不会有多余的请求,所以我想应该不是路由重复的问题:
exports.detail = function (req,res,next){
res.render('detail',{
title: 'hi'
});
};
GET /product/56335734f8e5b62182dc0d35 200
zhishifan started on port: 3000
GET /libs/jquery/dist/jquery.min.js 304
GET /libs/bootstrap/dist/css/bootstrap.min.css 304
GET /libs/bootstrap/dist/js/bootstrap.min.js 304
GET /js/comment.js 304
GET /libs/jquery/dist/jquery.min.map 304
你的detail函数无返回值