Node js no uploading formdata to server in react native while working fine in react js

Issue

Hi there I seriously need help for my mern stack application developed using expo react native.I am using string type form data to upload my image file to data base by uploading image to folder and saving name in data base my code is working fine in react js application but it is giving 404 bad request error in postman while using it with react native here is my code snippet:

petRoute.route('/pets/addpets').post( upload.any(), (req, res) => {
  try {
    if (
      req.files &&
      req.body &&
      req.body.name &&
      req.body.description &&
      req.body.price &&
      req.body.title &&
      req.body.selectedcity &&
      req.body.contact &&
      req.body.selectedcat
    ) {
      let new_product = new petModel();
      new_product.name = req.body.name;
      new_product.description = req.body.description;
      new_product.price = req.body.price;
      new_product.imgforsell = req.files[0].filename;
      new_product.title = req.body.title;
      new_product.selectedcat = req.body.selectedcat;
      new_product.contact = req.body.contact;
      new_product.selectedcity = req.body.selectedcity;

      //new_product.user_id = req.user.id;
      new_product.save((err, data) => {
        if (err) {
          res.status(400).json({
            errorMessage: err,
            status: false,
          });
        } else {
          res.status(200).json({
            status: true,
            title: "Product Added successfully.",
          });
        }
      });
    } else {
      res.status(400).json({
        errorMessage: "Add proper parameter first!",
        status: false,
      });
    }
  } catch (e) {
    res.status(400).json({
      errorMessage: "Something went wrong!",
      status: false,
    });
  }
});

Solution

I have found answer to my question problem was on service side:

I had not properly created a static folder which I later added following line

app.use(cors());
app.use('/image',express.static("uploads"));
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(
 bodyParser.urlencoded({
   // to support URL-encoded bodies
   extended: false,
 })
); 

Answered By – Saad Chaudry

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published