Upload image with Multer and Formik to Mongodb (MERN)

I created app using MERN. Now I'm trying to upload image with Multer and Formik, but req.file returns undefined, and I can't understand why. I'm new in this, but I guess this may cause from JSON.stringify (http.hook) or content-type: application/json. I also tried do this with FormData, but that's not working. Any ideas?

UPDATE: With Postman works good. I think problem is in ui part, input doesn,t pass the file.

app.js

const {Router} = require('express');
const multer = require('multer');
const auth = require('../middleware/auth.middleware');
const Users= require('../models/Users');
const router = Router();

const storage = multer.diskStorage({
   destination: function (req, file, cb) {
        cb(null, './client/public/uploads/');
   },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    },
});

const upload = multer({
    storage: storage,
    limits: { fileSize: 10 * 1024 * 1024 }
});


router.post('/create', upload.single('image'), auth, async (req, res) => {
    console.log(req.file);

    try {
        const code = req.body.code;

        const existing = await Users.findOne({code: code});

        if(existing) {
            return res.json({user: existing})
        }

        const user = new Users(req.body);

        await user .save();

        res.status(201).json(user);
    } catch (e) {
        console.log(e);
        res.status(500).json({ message: 'Error: try again.' })
    }
});

http.hook.js

import {useState, useCallback} from 'react';

export const useHttp = () => {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const request = useCallback(async (url, method = 'GET', body = null, headers = {}) => {
        setLoading(true);

        try {
            if(body) {
                body = JSON.stringify(body);
                headers['Content-Type'] = 'application/json';
            }

            const response = await fetch(url, {method, body, headers});
            const data = await response.json();

            if(!response.ok) {
                throw new Error(data.message || 'Something goes wrong')
            }

            setTimeout(() => {
                setLoading(false);
            }, 800);

            return data
        } catch (e) {
            setLoading(false);
            setError(e.message);

            throw e;
        }
    }, []);

    const clearError = useCallback(() => {setError(null)}, []);

    return {loading, request, error, clearError}};

CreateUser.js

import React, {useCallback, useContext, useEffect, useState} from 'react';
import {useHttp} from "../hooks/http.hook";
import Button from "../components/Button/Button";
import {AuthContext} from "../context/auth.context";
import {Formik} from "formik";

export const CreateUser = () => {
    const {token} = useContext(AuthContext);

    const {loading, request} = useHttp();

    const createUser = useCallback(async (body) => {
        try {
            const fetched = await request(`/api/user/create`, 'POST', body, {
                Authorization: `Bearer ${token}`
            });
        } catch (e) {console.log(e)}
    }, []);

    const handleCreate = (values, {resetForm}) => {
        console.log(values);
        createUser(values);
        // setModalVisibility(!modalVisibility.create);
        // resetForm({});
    };

    return (
        <div className="wrapper">
            <div className="row">
                <div className="column small-12 text-center color-white mb_45">
                    <div className="custom-headline text text-48 font-bold">
                        <h1>
                            Crate user
                        </h1>
                    </div>
                </div>
            </div>

            
                <Formik
                    enableReinitialize
                    initialValues={{
                        name: '',
                        code: '',,
                        image: null
                    }}
                    onSubmit={handleCreate}
                >
                    {({
                          values,
                          errors,
                          touched,
                          handleBlur,
                          handleChange,
                          handleSubmit,
                          isSubmitting,
                          setFieldValue,
                          resetForm
                      }) => (
                        <form onSubmit={handleSubmit} className="row align-center">
                            <div className="column small-12 large-7">
                                <div className="form-item flex-container align-middle mb_20">
                                    <label className="text text-14 font-semibold font-uppercase text-right small-4">
                                        Photos
                                    </label>
                                    <input id="image" type="file" name="image" className="file_input"
                                           onChange={(event) => {
                                               setFieldValue("image", event.currentTarget.files[0]);
                                           }} />
                                </div>
                            </div>

                            <div className="column small-12 large-7">
                                <div className="form-item flex-container align-middle mb_20">
                                    <label className="text text-14 font-semibold font-uppercase text-right small-4">
                                        Name
                                    </label>
                                    <input
                                        className="text text-17 "
                                        type="text"
                                        name="name"
                                        onChange={handleChange}
                                        onBlur={handleBlur}
                                        value={values.name}
                                    />
                                </div>
                            </div>
                            <div className="column small-12 large-7">
                                <div className="form-item flex-container align-middle mb_20">
                                    <label className="text text-14 font-semibold font-uppercase text-right small-4">
                                        Code
                                    </label>
                                    <input
                                        className="text text-17"
                                        type="text"
                                        name="code"
                                        onChange={handleChange}
                                        onBlur={handleBlur}
                                        value={values.code}
                                    />
                                </div>
                            </div>

                            <div className="column small-12 mt_20">
                                <div className="btn_group flex-container flex-wrap align-middle align-center">
                                    <Button className="btn-lg radius-8" theme="blue"
                                            text={Submit} type="submit"
                                    />
                                </div>
                            </div>
                        </form>
                    )}
                </Formik>
        </div>
    )
};


Read more here: https://stackoverflow.com/questions/67305676/upload-image-with-multer-and-formik-to-mongodb-mern

Content Attribution

This content was originally published by Erik P. at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: