Javascript Can';t从React前端将图片上传到MongoDb
我正在创建一个tinder克隆,我可以创建一个用户,但是我不能上传图片。我得到的错误是ValidationError:用户验证失败:图片:路径“图片”处的值“图片”转换为嵌入失败。我不确定我做错了什么。post请求似乎与有效负载一起触发,但当我收到错误时,它是在我登录时发出的。因此,我确信这与帐户的初始创建有关 前后创建帐户Javascript Can';t从React前端将图片上传到MongoDb,javascript,node.js,reactjs,mongodb,Javascript,Node.js,Reactjs,Mongodb,我正在创建一个tinder克隆,我可以创建一个用户,但是我不能上传图片。我得到的错误是ValidationError:用户验证失败:图片:路径“图片”处的值“图片”转换为嵌入失败。我不确定我做错了什么。post请求似乎与有效负载一起触发,但当我收到错误时,它是在我登录时发出的。因此,我确信这与帐户的初始创建有关 前后创建帐户 import React, { useState } from "react"; import {useHistory } from "rea
import React, { useState } from "react";
import {useHistory } from "react-router-dom";
import axios from "axios";
const CreateAccount = () => {
const api = "http://localhost:5000/user/create-account";
const history = useHistory();
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [emailAddress, setEmailAddress] = useState("");
const [password, setPassword] = useState("");
const [gender, setGender] = useState("Male");
const [sexualPreference, setSexualPreference] = useState("Straight");
const [age, setAge] = useState("");
const [description, setDescription] = useState("");
const [picture, setPicture] = useState("");
const account = {
firstName: firstName,
lastName: lastName,
emailAddress: emailAddress,
password: password,
gender: gender,
sexualPreference: sexualPreference,
age: age,
description: description,
pictures: picture
};
console.log(account.gender);
console.log(account.sexualPreference);
console.log(account.pictures)
const submit = () => {
axios
.post(api, account)
.then((res) => {
console.log(res.data);
history.push({
pathname: "/",
});
})
.catch((err) => console.log(err));
};
const handleSubmit = (event) => {
event.preventDefault();
submit();
};
return (
<div>
<div>
<h1>Create account</h1>
</div>
<form onSubmit={handleSubmit} encType="multipart/form-data">
<p>First Name</p>
<input
id="firstName"
name="firstName"
type="firstName"
onChange={(e) => setFirstName(e.target.value)}
></input>
<p>Last Name</p>
<input
id="lastName"
name="lastName"
type="lastName"
onChange={(e) => setLastName(e.target.value)}
></input>
<p>Email Address</p>
<input
id="emailAddress"
name="emailAddress"
type="emailAddress"
onChange={(e) => setEmailAddress(e.target.value)}
></input>
<p>Password</p>
<input
id="password"
name="password"
type="password"
onChange={(e) => setPassword(e.target.value)}
></input>
<p>Gender</p>
<select
id="gender"
name="gender"
type="gender"
onChange={(e) => setGender(e.target.value)}
>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<p>Sexual Preference</p>
<select
id="sexualPreference"
name="sexualPreference"
type="sexualPreference"
onChange={(e) => setSexualPreference(e.target.value)}
>
<option value="Straight" >Straight</option>
<option value="Gay" >Gay</option>
<option value="Lesbian" >Lesbian</option>
<option value="Bisexual" >Bisexual</option>
</select>
<p>Age</p>
<input
id="age"
name="age"
type="age"
onChange={(e) => setAge(e.target.value)}
></input>
<p>Description</p>
<input
id="description"
name="description"
type="description"
onChange={(e) => setDescription(e.target.value)}
></input>
<input
type="file"
name="file"
id="picture"
onChange={(e) => setPicture(e.target.id)}
></input>
<button type="submit">Submit</button>
</form>
</div>
);
};
export default CreateAccount;
mongoDb模式
const mongoose = require('mongoose');
const userSchema = mongoose.Schema( {
firstName:{
type: String,
required: true
},
lastName: {
type: String,
require: true
},
emailAddress: {
type: String,
require: true
},
password:{
type: String,
required: true
},
gender:{
type: String,
required: true
},
sexualPreference: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
description: {
type: String,
required: true
},
pictures: {
type: [{
picURL: String,
}],
},
matches: {
type: [{
Object
}],
},
})
module.exports = mongoose.model('User', userSchema);
登录后端和前端
router.post( "/login", asyncHandler(async (req, res, next) => {
const userBody = req.body;
const user = await User.findOne({ emailAddress: req.body.emailAddress });
if (userBody && user) {
console.log(user);
const authenticated = bcryptjs.compare(userBody.password, user.password);
console.log(authenticated);
if (authenticated) {
console.log("match");
const accessToken = jwt.sign(user.toJSON(), process.env.ACCESS_TOKEN_SECRET, { expiresIn: 86400 });
res.cookie("token", accessToken, { httpOnly: false, maxAge: 86400 });
res.setHeader('Authorization', 'Bearer '+ accessToken);
res.json({
user: user,
accessToken: accessToken,
})
.send()
} else {
res.status(403).send({ error: "Login failed: Please try again" }).end();
}
} else {
res.status(403).send({ error: "Login failed: Please try again" }).end();
}
})
);
import React,{useState}来自“React”;
从“react router”导入{useHistory};
从“axios”导入axios;
从“react router dom”导入{Link};
常数api=http://localhost:5000';
导出默认函数登录(){
const history=useHistory();
const[email,setEmail]=useState(“”);
const[pass,setPassword]=useState(“”);
常量提交=()=>{
post(`${api}/login`,{emailAddress:email,密码:pass},{withCredentials:true,credentials:'include'})
。然后(res=>{
setItem('jwt',res.data.accessToken);
历史推送({
路径名:`/user/account/${res.data.user.\u id}`
});
})
.catch(err=>console.log(err));
}
const handleSubmit=(事件)=>{
event.preventDefault();
提交()
}
返回(
登录
setEmail(e.target.value)}
/>
setPassword(e.target.value)}
/>
提交
取消
没有用户帐户吗?
点击这里
去报名吧!
);
}
首先,您不能像这样上传图像,因为您发送常规http请求。如果您想发送iamge,您需要按照以下步骤操作
在前端,您需要发送带有表单数据的请求以获取更多信息从mdn阅读此博客您可以使用axios将所有请求正文附加到表单数据,并将其添加到axios添加多部分/表单数据头中
axios({
method: "post",
url: "myurl",
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
// handle success
})
.catch(function (response) {
//handle error
});
在服务器中,您需要
import React, { useState} from "react";
import { useHistory } from "react-router";
import axios from "axios";
import { Link } from "react-router-dom";
const api = 'http://localhost:5000';
export default function Login () {
const history = useHistory();
const [ email, setEmail ] = useState("");
const [ pass, setPassword ] = useState("");
const submit = () => {
axios.post(`${api}/login`, { emailAddress: email, password: pass }, {withCredentials: true, credentials: 'include'})
.then(res => {
localStorage.setItem('jwt', res.data.accessToken);
history.push({
pathname: `/user/account/${res.data.user._id}`
});
})
.catch(err => console.log(err));
}
const handleSubmit = (event) => {
event.preventDefault();
submit()
}
return (
<div>
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<input
id="emailAddress"
name="emailAddress"
type="text"
placeholder="emailAddress"
onChange={(e) => setEmail(e.target.value)}
/>
<input
id="password"
name="password"
type="password"
placeholder="Password"
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit">Submit</button>
<button >Cancel</button>
</form>
<p>Don't have a user account?
<Link to="/user/create-account" >Click here</Link>
to sign up!
</p>
</div>
);
}
axios({
method: "post",
url: "myurl",
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
// handle success
})
.catch(function (response) {
//handle error
});