Всем привет. Подскажите, пожалуйста, как решить следующую проблему.
Отправляю данные с клиента на сервер:
finishEditHandler = postData => {
this.setState({
editLoading: true
});
// Set up data (with image!)
let formData = new FormData();
formData.append("title", postData.title);
formData.append("content", postData.content);
formData.append("image", postData.image);
console.log('formData title:', formData.getAll('title')); // ['title1']
console.log('formData content:', formData.getAll('content')); // ['content']
console.log('formData image:', formData.getAll('image'));
let url = 'http://localhost:8080/feed/post';
let method = 'POST';
if (this.state.editPost) {
url = 'URL';
}
fetch(url, {
method: method,
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify({
// title: postData.title,
// content: postData.content
// })
body: formData
})
.then(res => {
if (res.status !== 200 && res.status !== 201) {
throw new Error('Creating or editing a post failed!');
}
return res.json();
})
.then(resData => {
console.log(resData);
const post = {
_id: resData.post._id,
title: resData.post.title,
content: resData.post.content,
creator: resData.post.creator,
createdAt: resData.post.createdAt
};
this.setState(prevState => {
let updatedPosts = [...prevState.posts];
if (prevState.editPost) {
const postIndex = prevState.posts.findIndex(
p => p._id === prevState.editPost._id
);
updatedPosts[postIndex] = post;
} else if (prevState.posts.length < 2) {
updatedPosts = prevState.posts.concat(post);
}
return {
posts: updatedPosts,
isEditing: false,
editPost: null,
editLoading: false
};
});
})
.catch(err => {
console.log(err);
this.setState({
isEditing: false,
editPost: null,
editLoading: false,
error: err
});
});
};
На сервере обрабатываю данный route в контроллере createPost
exports.createPost = (req, res, next) => {
const errors = validationResult(req);
// console.log('req:', req);
console.log('req.body:', req.body); // {}
if (!errors.isEmpty()) {
const error = new Error('Validation failed, entered data is incorrect.');
error.statusCode = 422;
throw error;
// return res.status(422).json({
// message: 'Validation failed, entered data is incorrect.',
// errors: errors.array()
// });
}
// if (!req.file) {
// const error = new Error('No image provided.');
// error.statusCode = 422;
// throw error;
// }
// const imageUrl = req.file.path;
const title = req.body.title;
const content = req.body.content;
// Create post in db
// res.status(201).json({
// message: 'Post created successfully!',
// post: {
// _id: new Date().toISOString(),
// title: title,
// content: content,
// creator: {
// name: 'Vyacheslav'
// },
// createdAt: new Date()
// }
// });
const post = new Post({
title: title,
content: content,
imageUrl: 'images/showcase.jpg', // 'images/showcase.jpg' // imageUrl
creator: {
name: 'author'
}
});
post.save()
.then(result => {
// console.log(result);
res.status(201).json({
message: 'Post created successfully!',
post: result
});
})
.catch(err => {
// console.log(err);
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
});
};
Но в
console.log('req.body:', req.body); // {}
приходит пустой объект.