G
G
gsdev992019-05-01 13:43:15
JavaScript
gsdev99, 2019-05-01 13:43:15

How to correctly accept data (FormData)?

Hello. Please tell me how to solve the following problem.
Sending data from client to server:

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
            });
        });
};

On the server, I process this route in the createPost controller
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);
        });
};

But in
console.log('req.body:', req.body); // {}
comes an empty object.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stockholm Syndrome, 2019-05-01
@gsdev99

try using multer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question