我做了一个登录和注册系统。但是,用户简介照片有一个问题。如果用户不想添加配置文件照片,那么该用户的配置文件照片将为空。但我犯了个错误。
这是我的个人资料user.js的一部分
profile:{
type: String,
}和这是我注册的相关的帖子路径.
let user= new User({
username: req.body.username,
email: req.body.email,
password: hashedPassword,
profile: req.file.path.replace(/^public/, '')
});,最后这是我的register.pug:
.file-field.input-field(method="post")
.btn.grey
label Profile Photo
input(name='profile', type='file', enctype="multipart/form-data")但是,当我提交时没有选择任何个人资料照片,它会给出以下错误:
(节点:26436) UnhandledPromiseRejectionWarning: TypeError:无法读取未定义的属性“路径”
但为什么会这样呢?我已经取消了个人资料照片作为不需要。那么,如果我不想上传个人资料照片,它为什么要搜索路径呢?
发布于 2020-06-19 15:33:38
在对用户对象设置req.file之前,您可以验证它是否存在,如果没有,则将其设置为空字符串
let user= new User({
username: req.body.username,
email: req.body.email,
password: hashedPassword,
profile: req.file ? req.file.path.replace(/^public/, '') : ""
});https://stackoverflow.com/questions/62473319
复制相似问题