// @route GET api/profile/handle/:handle
// @desc Get profile by handle
// @access Public
router.get('/handle/:handle', (req, res) => {
const errors = {};
Profile.findOne({ handle: req.params.handle })
.populate('user', ['name', 'avatar'])
.then(profile => {
//console.log('profile1 ' + profile);
if (!profile) {
errors.noprofile = 'There is no profile for this user for handle route (from then block)';
res.status(404).json(errors);
}
res.json(profile);
})
.catch(err => res.status(404).json({ profile: 'There is no profile for this user for handle route (from error block)' }));
});
// @route GET api/profile/user/:user_id
// @desc Get profile by user ID
// @access Public
router.get('/user/:user_id', (req, res) => {
const errors = {};
Profile.findOne({ user: req.params.user_id })
.populate('user', ['name', 'avatar'])
.then(profile => {
// console.log('profile not found by userid');
//console.log('profile2 ' + profile);
if (!profile) {
errors.noprofile = 'There is no profile for this user for user_id route (from then block)';
res.status(404).json(errors);
}
res.json(profile);
})
.catch(err => res.status(404).json({ profile: 'There is no profile for this user for user_id route (from error block)',
err: err }));
});
我有以上两条路线。第一个是使用handle(用户名)从dB搜索用户,第二个是使用dB本身创建的user_id搜索。当我使用错误的句柄请求第一条路线时,then()块将被执行,并且得到以下响应:
{
"noprofile": "There is no profile for this user for handle route (from then block)"
}
但是在第二条路线(通过user_id搜索)中,当我输入错误的user_id时,catch块被执行,并且得到以下响应:
{
"profile": "There is no profile for this user for user_id route (from error block)",
"err": {
"message": "Cast to ObjectId failed for value \"5cb0ec06d1d6f93c20874427rhdh\" at path \"user\" for model \"profile\"",
"name": "CastError",
"stringValue": "\"5cb0ec06d1d6f93c20874427rhdh\"",
"kind": "ObjectId",
"value": "5cb0ec06d1d6f93c20874427rhdh",
"path": "user"
}
}
两条路线的逻辑相同,但是它们的响应方式不同。这背后的原因是什么???
如果要查看Profile模式,则为:
const ProfileSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
handle: {
type: String,
required: true,
max: 40
},
company: {
type: String
},
....
....
.....
});
请求错误的句柄时,我也收到警告:
(node:16996) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (H:\MERN Stack Course\devConnector\node_modules\express\lib\response.js:767:10)
at ServerResponse.send (H:\MERN Stack Course\devConnector\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (H:\MERN Stack Course\devConnector\node_modules\express\lib\response.js:267:15)
at Profile.findOne.populate.then.catch.err (H:\MERN Stack Course\devConnector\routes\api\profile.js:75:39)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:16996) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:16996) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
最佳答案
检查错误消息
"message": "Cast to ObjectId failed for value \"5cb0ec06d1d6f93c20874427rhdh\" at path \"user\" for model \"profile\""
user
字段是mongodb类型ObjectId
,而您要提供String
,而handle
是String
类型如果是
handle
查询,则没有错误,只有db
中没有条目。您可以像
mongoose.Types.ObjectId(req.params.user_id)
一样修复它。 More here另外,您的代码也有问题。 (执行不会在您认为停止的地方停止,并且您会遇到无法处理的承诺拒绝)
.then(profile => {
//console.log('profile1 ' + profile);
if (!profile) { // <--- if true
errors.noprofile = 'There is no profile for this user for handle route (from then block)';
res.status(404).json(errors); // <-- executes
}
res.json(profile); // <--- always executes within then callback
})
如果此检查
if (!profile)
评估为true
,则将执行res.status(404).json(errors)
。然后执行下一个res.json(profile)
。在您的代码中,总是在没有错误的情况下执行
res.json(profile)
。您可以通过使用return
停止执行或if..else
进行纠正,例如:return res.status(404).json(errors);
// or
if (!profile) {
errors.noprofile = 'There is no profile for this user for handle route (from then block)';
res.status(404).json(errors);
} else {
res.json(profile);
}