【发布时间】:2021-04-17 21:08:08
【问题描述】:
当我使用邮递员上传图片时,api 工作正常。并且图像被上传。但是当我尝试将数据从前端(反应)发送到后端(nodejs)时,这个错误不断发生。无法读取未定义的属性“路径”。但是当我控制台记录上传图片的值时,我会得到这样的文件路径“C:\fakepath\moneyIcon.png”
这是我的反应代码:
handleSubmit = (e) => {
e.preventDefault();
const data = new FormData();
data.append("file", this.state.Logo);
console.log(data);
console.log(`
--SUBMITTING--
First Name: ${this.state.firstName}
Last Name: ${this.state.lastName}
Email: ${this.state.email}
Password: ${this.state.password}
Logo:${this.state.Logo}
`);
console.log(this.state.Logo);
const registered = {
firstName: this.state.firstName,
lastName: this.state.lastName,
email: this.state.email,
password: this.state.password,
ConfirmPassword: this.state.ConfirmPassword,
CompanyName: this.state.CompanyName,
Website: this.state.Website,
PhoneNumber: this.state.PhoneNumber,
Adress: this.state.Adress,
CompanyDescription: this.state.CompanyDescription,
Logo: data,
};
axios
.post("http://localhost:4000/app/company-registration", registered)
.then((response) => {
console.log(response.data);
if (response.status == 200) {
console.log("Successfully Registered");
this.setState({
firstName: "",
lastName: "",
email: "",
password: "",
date: "",
error: "",
Logo: "",
});
}
})
.catch((err) => {
console.log(err);
this.setState({
error: "Company already exists",
});
});
};
onChangeHandler = (event) => {
this.setState({
Logo: event.target.value,
});
};
<div className="firstName">
<label htmlFor="Logo">Logo</label>
<input
type="file"
className="campanyLogo"
name="logo"
accept=""
onChange={this.onChangeHandler}
/>
</div>
这是 nodejs api
router.post('/company-registration', upload.single('Logo'),async (request, response) => {
console.log(request.file)
let user = await Company.findOne({ email: request.body.email });
if (user) {
return response.status(400).json('That company already exisits!');
} else {
// Insert the new user if they do not exist yet
companyuser = new Company({
firstName:request.body.firstName,
lastName:request.body.lastName,
CompanyName: request.body.CompanyName,
Website: request.body.Website,
PhoneNumber: request.body.PhoneNumber,
Adress: request.body.Adress,
email:request.body.email,
password:request.body.password,
Logo: request.file.path,
Sector: request.body.Sector,
})
}
const saltPassword = await bcrypt.genSalt(10)
companyuser.password = await bcrypt.hash(request.body.password, saltPassword)
await companyuser.save()
.then(data => {
response.json(data)
})
.catch(error => {
response.json(error)
})
})
【问题讨论】:
-
不,不是这样:/我已经改了,但还是一样的错误。
标签: node.js reactjs express file-upload