0

I am trying to send an image in a POST req from react to nodejs. However my back-end is not receiving the file and req.file is undefined. When I test the server image upload code with postman, everything works fine so I suspect something is wrong on the front-end. Anybody know what's wrong? Here's my code:

Image_Upload.js (submit image func, fileList[0] is an image):

 onSubmitImage = e => {
    const config = {
      headers: {
        "content-type": "multipart/form-data"
      }
    };
    const formData = new FormData();
    formData.append(
      "image",
      this.state.fileList[0]
    );
    axios
      .post("/api/profile/img_upload", formData)
      .then(res => console.log("Response: " + res))
      .catch(err => console.log(err.response.data));
  };

profile.js (receiving image endpoint):

router.post(
  "/img_upload",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    upload(req, res, err => {
      console.log(req);
      if (err) {
        res.status(400).json({ Error: err });
      } else {
        if (req.file == undefined) {
          res.status(404).json({ error: "no file selected" });
        } else {
          res.json({ fileLoc: req.file.location });
        }
      }
    });
  }
);

img_upload.js (multer setup):

const upload = multer({
  storage: storage,
  limits: { fileSize: 1000000 },
  fileFilter: function(req, file, cb) {
    checkFileType(file, cb);
  }
}).single("image");

Any help is appreciated

EDIT: I am noticing that when nodejs receives the req from the front-end, it is in req.body instead of req.file. So I am positive the problem is in react. How can I get react to send it as req.file instead of req.body? Image request from Reacdt Front-end to Nodejs backend

Community
  • 1
  • 1
sh_crp
  • 71
  • 1
  • 8

1 Answers1

0

upload that you defined is actually an express middleware which must take 3 arguments: request, response and next, respectively. next() calls the subsequent middleware in case no errors or next(error) otherwise. I highly recommend checking the answers to this question to get a better idea.

What you have done here is that you're calling a middleware as if it was a method. To fix that, config multer first

const multer  = require('multer');
const upload = multer({
  storage: 'path/here/',
  limits: { fileSize: 1000000 },
  fileFilter: function(req, file, cb) {
    checkFileType(file, cb);
  }
});

then

router.post("/img_upload",
  passport.authenticate("jwt", { session: false }),
  upload.single('image'),
  (req, res) => {
  // Your code here
});
Aziz
  • 38
  • 1
  • 7
  • Thanks, this solution worked with postman but req.file is still undefined when the image is sent from the react front-end. I added a screen shot of the req to my post – sh_crp Feb 03 '19 at 19:39