当前位置: 首页 > 知识库问答 >
问题:

在这段代码中,我对两条路由有相同的逻辑,但它们的行为不同

裴展
2023-03-14
// @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 }));
});

我有上述两条路线。第一个是使用句柄(用户名)从dB中搜索用户,第二个是使用dB本身创建的用户id进行搜索。当我使用错误的句柄请求第一条路由时,会执行then()块,并得到以下响应:

{
    "noprofile": "There is no profile for this user for handle route (from then block)"
}

但在第二条路径(按用户id搜索)中,当我输入错误的用户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.

共有2个答案

轩辕瑞
2023-03-14

我认为在您的第二个路由中,您试图使用无效的ObjectID进行查询。

请检查:什么是Mongoose错误Cast to ObjectId失败的值XXX在路径"_id"?

谢承颜
2023-03-14

检查错误消息

"message": "Cast to ObjectId failed for value \"5cb0ec06d1d6f93c20874427rhdh\" at path \"user\" for model \"profile\""

user字段是mongob类型的ObjectId,您提供的是String,而句柄是类型String

对于handle查询,没有错误,只是db中没有条目。

你可以像猫鼬一样修复它。类型。ObjectId(req.params.user_id).这里更多

还有,你的代码有问题。(执行不会在你认为停止的地方停止,你会得到未经处理的promise拒绝)

.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(!配置文件计算为true,然后执行res.status(404). json(错误)。然后执行下一个res.json。

在您的代码中,res.json(profile)总是在没有错误时执行。您可以通过使用return停止执行或如果。。其他如:

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);
}
 类似资料:
  • 这两个代码的行为都会在值不存在时引发异常。 我想知道这两个代码之间的区别。

  • 问题内容: 我有下面的代码。我只想检查代码块的运行时间。错误地,我再次复制并粘贴了相同的代码,并得到了有趣的结果。尽管代码块相同,但运行时间不同。而且 比其他人花费更多的时间。如果我切换代码块,则代码块4将比其他代码花费更多时间。 我在代码块中使用了两种不同类型的数组来检查它是否依赖于此。结果是一样的。如果代码块具有相同类型的数组,则最上面的代码块将花费更多时间。参见下面的代码和给出的输出。 运行

  • 本文向大家介绍两个对象值相同equals结果为true,但却可有不同的 hashCode,这句话对不对?相关面试题,主要包含被问及两个对象值相同equals结果为true,但却可有不同的 hashCode,这句话对不对?时的应答技巧和注意事项,需要的朋友参考一下 不对,如果两个对象x和y满足x.equals(y) == true,它们的哈希值(hashCode)应当相同。Java 对于equals

  • 我正在为我的discord机器人制作一个管理cog,我的代码无法识别“ctx”。PyCharm建议用“self”代替“ctx”,我不知道“self”是做什么的。从PyCharm所说的,还有数以百万计的其他东西,我必须写下它是什么。PyCharm无法识别帮会、发送、作者和频道,它还说是一个无法访问的代码。请注意,如果这似乎是一个非常愚蠢的问题,我是一个初学者,两周前就开始了。 至于代码:

  • 根据逻辑,我需要实现两个,如果它们以相同的“相对”顺序具有相同的元素,则它们被认为是相等的。 举个例子,以下一对列表被认为彼此相等: 只要遵守相对顺序,就可以认为它们是平等的。 作为反例,这两个不相等: 导致 和 交换到位。 所以,基本上我发现这很有挑战性,因为这不是顺序完全重要的情况,也不是顺序完全不重要的情况。在这种情况下,我会使用普通的< code>list1.equals(list2)方法