Profil supprimé | Je serre. Mon problème alors. Je fais une requête Fetch pour mettre à jour ma base de données se trouvant chez MongoDB, cela fonctionne parfaitement en Content-Type: application/json, mais pas lorsque je veux utiliser FormData() pour l'envoi ensuite d'images.
Mon code côté front (React) :
Code :
- function ModalPageMyProfile() {
- const authContext = useContext(AuthContext)
- const [dataResult, setDataResult] = useState({})
- const regexFormChangeFirstName = (e) => {
-
- const newDataResult = {...dataResult}
- newDataResult.firstname = e.target.value
- setDataResult(newDataResult)
-
- RegexFunctionChange.infoInvisible('#signUpFirstName', '#alertInfoFirstName', '#alertInfoArrowFirstName', 'alertInfoMinLetterInvisible', 'alertInfoFirstNameMinLetterVisibleModalMyProfile',
- 'alertInfoArrowInvisible', 'alertInfoFirstNameArrowVisibleModalMyProfile')
- RegexFunctionChange.firstName('#signUpFirstName')
- // if (e.target.value.match(/^[a-zA-Z-]{2,25}$/)) {
- // valueFirstName = e.target.value
- // console.log(valueFirstName)
- // }
- // else {
- // valueFirstName = null
- // }
- }
-
- const regexFormChangeLastName = (e) => {
-
- const newDataResult = {...dataResult}
- newDataResult.lastname = e.target.value
- setDataResult(newDataResult)
-
-
- RegexFunctionChange.infoInvisible('#signUpLastName', '#alertInfoLastName', '#alertInfoArrowLastName', 'alertInfoMinLetterInvisible', 'alertInfoLastNameMinLetterVisibleModalMyProfile',
- 'alertInfoArrowInvisible', 'alertInfoLastNameArrowVisibleModalMyProfile')
- RegexFunctionChange.lastName('#signUpLastName')
-
-
- // if (e.target.value.match(/^[a-zA-Z-]{2,25}$/)) {
- // valueLastName = e.target.value
- // }
- // else {
- // valueLastName = null
- //}
- }
- const formData = new FormData()
- const dataObject = {...dataResult}
- formData.append('infosUser', JSON.stringify(dataObject))
- //formData.append('Authorization', `Bearer ${authContext.token}`)
- console.log(formData.get('infosUser'))
- const fetchPut = () => {
- if (dataResult.firstname.match(/^[a-zA-Z-]{2,25}$/) &&
- dataResult.lastname.match(/^[a-zA-Z-]{2,25}$/)) {
- // const fetchHandlerUpdate = async () => {
- // const response = await
- fetch(urlPut,
- {
- method: 'PUT',
- headers: {
- //'Content-Type': 'application/json',
- 'Accept': 'application/json',
- 'Authorization': `Bearer ${authContext.token}`
- },
- body: formData
- })
- .then( response => response.json())
- .then ( data => console.log(data))
- // const data = await response.json( );
- // if(response.ok) {
- // console.log(data)
- // }
-
- }
- // fetchHandlerUpdate()
- // }
- }
- return (
- <DivNameProfile>
- <DivNameInput>
-
- <input name={'firstName'} placeholder={dataResult.firstname} value={dataResult.firstname || ' '} id={'signUpFirstName'} className={'inputsNameMyProfile input'} onBlur={regexBlurFirstName} onChange={regexFormChangeFirstName}></input>
-
- </DivNameInput>
- <DivNameInput>
-
- <input name={'lastName'} placeholder={dataResult.lastname} value={dataResult.lastname || ' '} id={'signUpLastName'} className={'inputsNameMyProfile input'} /*onFocus={() => test()}*/ onBlur={regexBlurLastName} onChange={regexFormChangeLastName}></input>
-
- </DivNameInput>
- </DivNameProfile>
- <ButtonValidation onClick={() => fetchPut()}/>
- )
- }
|
Rendus console côté front (le state se met à jour nickel :
Code :
- {"_id":"6357f144a5ac260a67a5a9c9","firstname":"Jzaaaeeedd","lastname":"Jza","email":"jerome@truc.fr","password":"$2b$10$LY7dWK65f9Xs1PKD8Oy.c./OJZy1rPfNturFRGlaYQW0hzelNK0FS","bioProfile":"","city":"","imageUrlProfilePicture":"","imageUrlLandscapePicture":"","admin":false,"__v":0}
- {message: 'Objet modifié !'}
|
Middleware côté back :
Code :
- exports.modifyInfosUser = (req, res) => {
- const userObject = req.file ? {
- ...JSON.parse(req.body.infosUser),
- imageUrlProfilePicture: `${req.protocol}://${req.get('host')}/images/${req.file.filename}`
- } : { ...req.body };
- console.log(req.body.infosUser)
- delete userObject.userId;
- User.findOne({ _id: req.params.id})
- .then((user) => {
- if ( user._id != req.auth.userId) {
- res.status(401).json({ message:'Non-autorisé' })
- } else {
- User.updateOne({ _id: req.params.id }, { ...userObject, _id: req.params.id }, {returnNewDocument: true}/*, {returnOriginal:false}*/)
- .then(() => res.status(200).json({ message: 'Objet modifié !' }))
- .catch((error) => res.status(403).json({ error }));
- console.log(req.body)
- }
- })
- .catch((error) => res.status(400).json({ error }))
- }
|
Rendus console côté back :
Code :
- {
- userId: '6357f144a5ac260a67a5a9c9',
- iat: 1666973805,
- exp: 1667002605
- }
- {"_id":"6357f144a5ac260a67a5a9c9","firstname":"Jzaaaeeedd","lastname":"Jza","email":"jerome@truc.fr","password":"$2b$10$LY7dWK65f9Xs1PKD8Oy.c./OJZy1rPfNturFRGlaYQW0hzelNK0FS","bioProfile":"","city":"","imageUrlProfilePicture":"","imageUrlLandscapePicture":"","admin":false,"__v":0}
|
Et mes CORS :
Code :
- app.use((req, res, next) => {
- // res.setHeader('Access-Control-Allow-Origin', '*');
- // res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
- // res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
- res.header("Access-Control-Allow-Origin", "*" );
- res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
- res.header("Access-Control-Allow-Headers", "X-Requested-With, X-HTTP-Methods-Override, Content-Type, Accept,Cache-Control, Pragma, Origin, Authorization, Content-Type, form-data" );
- res.header("Access-Control-Allow-Credentials", "true" );
- if ('OPTIONS' == req.method){
- return res.send(200);
- }
- next();
- });
- app.use(express.json());
- app.use('/', usersRoutes)
- app.use('/images', express.static(path.join(__dirname, 'images')));
- app.use(express.urlencoded({ extended: true }));
- module.exports = app;
|
Voilà, plus de deux jours sur ça comme un noob, en faisant recherche sur recherche, test sur test, sans trouver l'origine du truc.
Toute aide est plus que la bienvenue |