简体   繁体   English

为什么这个 if 语句不起作用?

[英]Why isn't this if statement functioning?

I am relatively new to development and am unfamiliar with lingo or how to properly ask questions.我对开发比较陌生,不熟悉行话或如何正确提问。 I am attempting to create a put request to update a profile image using express-fileupload.我正在尝试使用 express-fileupload 创建一个 put 请求以更新配置文件图像。 If I don't include the fist if statement, console returns null and nothing renders or saves.如果我不包含第一个 if 语句,控制台会返回 null 并且不会呈现或保存任何内容。 As is, the app crashes.照原样,应用程序崩溃。 I'm hoping simply posting the code here will suffice for someone to see what the issue is.我希望只需在此处发布代码就足以让某人看到问题所在。 Thanks ahead of time for helping a newbie.提前感谢您帮助新手。

router.put("/artistsbe/:id", middleware.isLoggedIn, function(req, res){
Artists.findByIdAndUpdate(req.params.id, req.body, function(err, artist){
    if(req.files != "null"){
        let image = req.files.artistImage;
        image.mv("./public/images/" + req.files.artistImage.name, function(err){
            if(err){
                console.log(err);
            }
        });
    } else {
        res.redirect("back");
    }
});

}); });

I think you just need to do:我认为你只需要这样做:

if(req.files) {

This will evaluate as truthy if files is not undefined null false or other falsey values.如果files不是undefined null false或其他 falsey 值,这将评估为真。

The problem you have is that you are comparing req.files to a string "null" .您遇到的问题是您正在将req.files与字符串"null"进行比较。 Instead, you should compare against the type null .相反,您应该与类型null进行比较。

Also, you may also want to check for undefined .此外,您可能还想检查undefined What you can do is write something like this:你可以做的是这样写:

if (req.files) {... }

This way, you will check if req.files is not null nor undefined (and also false , but I don't think this variable should receive a boolean value, but you never know...)这样,您将检查 req.files 是否不是null也不是undefined (也是false ,但我认为这个变量不应该收到 boolean 值,但你永远不知道......)

Hope my answer was helpful希望我的回答有帮助

Try this尝试这个

router.put("/artistsbe/:id", middleware.isLoggedIn, function(req, res){
Artists.findByIdAndUpdate(req.params.id, req.body, function(err, artist){
if(req.files){
    let image = req.files.artistImage;
    image.mv("./public/images/" + req.files.artistImage.name, function(err){
        if(err){
            console.log(err);
        }
    });
} else {
    res.redirect("back");
}
});

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM