1

I am trying to send a photo from react to node server.

But i have some problems : req.file is undefined and I don't understand why

This is my react code

const formData: any = new FormData();

formData.append("file", {
  uri: image.uri,
  type: image.type,
  name: "tmpImage",
});

try {    
  await axios.post(`${BACKEND_URL}/recipes/photo`, {
    formData,
    header: { "Content-Type": "multipart/form-data" },
  });

} catch (error) {
  console.error("Error when sending image");
}

and here is my nodejs code

multer conf :

export const storage = multer.diskStorage({
  destination: function (req, file, callback) {
    console.log("here dest");
    callback(null, "uploads");
  },
  filename: function (req, file, callback) {
    console.log("here filename");
    callback(null, file.originalname);
  },
});

export const upload: any = multer({ storage });

route :

recipesRoutes.post(
  "/photo",
  upload.single("tmpImage"),
  async (req: Request, res: Response) => {
    console.log("req files =>", req.files);
    console.log("req file =>", req.file);

    return res.status(200).send();
  }
);

express conf :

app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

req.file is undefined and I don't understand why.

Thanks for help

Jim
  • 669
  • 4
  • 10
  • 24
  • Please see [ask], then revise your post title to ask a clear, specific question in sentence format. – isherwood Nov 02 '22 at 18:32
  • Probably you need some middleware to handle files sent as a form-data. Take a look [here](https://stackoverflow.com/questions/23114374/file-uploading-with-express-4-0-req-files-undefined) – Konstantin Mironov Nov 02 '22 at 18:43
  • Already tried bodyparser. Same result. But im gonna try asap again – Jim Nov 02 '22 at 18:47

1 Answers1

0

I think you need to use the different curly brackets for the data that you are sending and the headers that you configuring. it must be something like this:

 await axios.post(`${BACKEND_URL}/recipes/photo`,
       {formData},
       {header: { "Content-Type": "multipart/form-data" }},
 );

based on this example :

import axios from 'axios';

axios.post('https://httpbin.org/post', {x: 1}, {
headers: {
'Content-Type': 'multipart/form-data'
 }
 }).then(({data}) => console.log(data));

on this page

GitHub

Farbod Shabani
  • 422
  • 4
  • 9