How to send extra input value from form data in react native then show it on backend node js

Viewed 192

Hello I am trying to upload photo to the server , and photo is uploading on the node js server but I want to add extra field with file name like _id so that I can update photo name to the mongodb js , but I am not getting the _id in backend even when I am sending with form-data

here is my front end

const postImage = async (image) => {
setIsloaded(true);
console.log("Image",image)
const photo = {
  uri: image.uri,
  type: "image/jpg",
  name: "avatar",
  u_id:u_id
};

 const ids = {
  u_id:{u_id}
};

const data = new FormData();
data.append('file', photo);
data.append('ids', ids);

const config = {
  method: 'POST',
  body: data,
  headers: {
    Accept: 'application/json',
    // 'Content-Type': 'image/jpeg',
    'Content-Type': 'multipart/form-data',
  },
};
 fetch("https://127.0.0.1:3000/updateImageprofile", config)
 .then((responseData) => {
  console.log("Succes "+ responseData)
})
.catch((error) => {
  console.log("ERROR " + error)
});

}

and here is my backend using node js

    router.post("/updateImageprofile", upload.single('file'), async (req, res,next) => {

  console.log("body =>", req.body);
  console.log('files => ', req.files);
  console.log("file =>", req.file);
  console.log("id =>", req.ids);
    res.sendStatus(200);
  });

My data showing in console like below

 data FormData {
  "_parts": Array [
    Array [
      "file",
      Object {
        "name": "avatar",
        "type": "image/jpg",
        "u_id": "5e831c424ca3a00b6c78311a",
        "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540satya89310%252Fembteen/ImagePicker/05af4bc2-5883-48e0-8abb-91281b4a9b7d.jpg",
      },
    ],
    Array [
      "ids",
      Object {
        "u_id": Object {
          "u_id": "5e831c424ca3a00b6c78311a",
        },
      },
    ],
  ],
}

I am what getting on the console from node js is below

    file => {
  fieldname: 'file',
  originalname: 'avatar',
  encoding: '7bit',
  mimetype: 'image/jpg',
  destination: 'upload/',
  filename: '39e461c3055e24921ca705efcbc48600',
  path: 'upload\\39e461c3055e24921ca705efcbc48600',
  size: 221702
}
id => undefined

id value is showing null here how to get id value which I am sending from front end

1 Answers

In your path you are asking for 'file' not for 'ids'. Try:

router.post( "/updateImageprofile", upload.any([ 'file', 'ids' ]), ...
Related