Search code examples
node.jsexpressmultipartform-datamulter

404 Not Found on express route when sending files


I'm having a hard time fixing this 404 Not found error, so i'm sending files to my express server with FormData api without using a form. Whenever i trigger a request with files in the payload i get 404 (Not Found) SyntaxError: Unexpected token < in JSON at position 0 but if i trigger the request without sending any file it gives me the response properly.. can anyone help? controller

   update: (req, res) => {
       console.log(req.files)
        res.json({
            status: 'test',
            code: 200
        })
    }

route

router.post('/update', account.update);

my request

 saveUpdate = () => {
        const formData = new FormData();
        const { user, Auth } = this.props;
        formData.append('user_id', user.id);
        formData.append('photo', this.photo_ref.files[0]);
        formData.append('cover', this.cover_ref.files[0]);

        Auth.fetch('/update', {
            method: "POST",
            credentials: 'same-origin',
            body: formData,
        })
        .then(res => {
            if(res.code === 200){
                console.log(res)
            }
        })
        .catch(err => console.log(err));
    }

devtools gives me correct information about my request if i send the request with files it shows the payload correctly , the content-type is also correct which is multipart/form-data but it still gives me the above error. If i don't send any files i get the proper server response any idea?

I am using multer package In this order

server.use(express.static(path.resolve(__dirname, '../public')));
server.use(multer({storage}).array('image', 12));
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json());
server.use('/', router);

Solution

  • It seems like you are not providing the name parameter correctly. You can append these two image with the same name

    Instead of of this

     formData.append('photo', this.photo_ref.files[0]);
     formData.append('cover', this.cover_ref.files[0]);
    

    You can do

     formData.append('image', this.photo_ref.files[0]);
     formData.append('image', this.cover_ref.files[0]);