【问题标题】:I am getting two errors front end errorm AxiosError: Request failed with status code 500 Backend error PayloadTooLargeError: request entity too large我收到两个错误前端错误 AxiosError: Request failed with status code 500 Backend error PayloadTooLargeError: request entity too large
【发布时间】:2022-08-03 20:09:24
【问题描述】:

我正在尝试使用 Reactnative 开发 Mern Stack 移动应用程序我从前端收到两个错误

AxiosError:请求失败,状态码为 500 来自节点 PayloadTooLargeError 的后端错误:请求实体太大

我现在尝试了不同的方法来发布数据我正在使用 formdata 来附加代码和 axios 来发布代码

这是前端代码:


export default class Sellnow extends Component {
  constructor(props) {
    super(props);
    this.onChangePetName = this.onChangePetName.bind(this);
    this.onChangePetTitle = this.onChangePetTitle.bind(this);
    this.onChangePetContact = this.onChangePetContact.bind(this);
    this.onChangePetPrice = this.onChangePetPrice.bind(this);
    this.onChangePetDescription = this.onChangePetDescription.bind(this);
    this.onValueChangeCat= this.onValueChangeCat.bind(this);
    this.onValueChangeCity= this.onValueChangeCity.bind(this);
    this.onFileChange = this.onFileChange.bind(this);
   // this.pickImage = this.pickImage.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    // State
    this.state = {
      name: \"\",
      title: \"\",
      contact: \"\",
      price: \"\",
      description: \"\",
      selectedcat:\"\",
      selectedcity:\"\",
      imgforsell:\"\",

      //collection categories
      category: [
        
        {
          itemName: \"Select Category....\"
        },
        {
          itemName: \"Pets Food\"
        },
        {
          itemName: \"Pets Products\"
        },
        {
          itemName: \"Pets Accessories\"
        }
      ],

      // cities category
      cityCategory:[


        {
          itemName: \"Select City....\"
        },
        {
          itemName: \"Islamabad\"
        },
        {
          itemName: \"Rawalpindi\"
        },
        {
          itemName: \"Lahore\"
        },
        {
          itemName: \"Peshawar\"
        },
        {
          itemName: \"Karachi\"
        },
        {
          itemName: \"Quetta\"
        }

      ]
    };
  }


  /*componentDidMount() {
    axios.get(\'http://localhost:3000/PetsBazar/pets/\' )
      .then(res => {
        this.setState({
          name: res.data.name,
          title: res.data.title,
          contact: res.data.contact
        });
      })
      .catch((error) => {
        console.log(error);
      })
  }*/
  onChangePetName(e) {
    this.setState({ name: e.target.value });
  }
  onChangePetTitle(e) {
    this.setState({ title: e.target.value });
  }
  onChangePetContact(e) {
    this.setState({ contact: e.target.value });
  }
  onChangePetPrice(e) {
    this.setState({ price: e.target.value });
  }
  onChangePetDescription(e) {
    this.setState({ description: e.target.value });
  }
  // categories function
  onValueChangeCat(e) {
    this.setState({ selectedcat: e.targetvalue })
  }

  // city function
  onValueChangeCity(e) {
    this.setState({ selectedcity: e.targetvalue })
  }

  onFileChange(e) {
    this.setState({ imgforsell: e.targetvalue})}

  // uploading Image


  _getPhotoLibrary = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: true,
      base64: true,
      exif: true,
      aspect: [4, 3]
    });

    

    if (!result.cancelled) {
      this.setState({ imgforsell: result });
      
      
    }
    this.props.navigation.setParams({
      imgforsell: this.state.imgforsell
    });
  };

  


  async onSubmit() {
   // e.preventDefault();
    /*const petsObject = {
      name: this.state.name,
      title: this.state.title,
      contact: this.state.contact,
      price: this.state.price,
      description: this.state.description,
      selectedcat:this.state.selectedcat,
      selectedcity:this.state.selectedcity,
      imgforsell:this.state.imgforsell
      };
*/




      //const formData = new FormData();
      
      // const FormData = global.FormData;
      const formData = new FormData();
      formData.append(\"name\", this.state.name);
      /*formData.name = this.state.name,
      formData.title = this.state.title
      formData.contact = this.state.contact
      formData.price = this.state.price
      formData.description = this.state.description
      formData.selectedcat = this.state.selectedcity
      formData.imgforsell= this.state.imgforsell*/
      //formData.append(\"name\",name);
      
      formData.append(\"title\", this.state.title);

      //formData.append(\"title\", title);
      
      formData.append(\"contact\", this.state.contact);

      //formData.append(\"contact\", contact);
     
     formData.append(\"price\", this.state.price);

     // formData.append(\"price\", price);
     
       formData.append(\"description\", this.state.description);

      //formData.append(\"description\", description);
     
      formData.append(\"selectedcat\", this.state.selectedcat);

      //formData.append(\"selectedcat\", selectedcat);
     
       formData.append(\"selectedcity\", this.state.selectedcity);

     // formData.append(\"selectedcity\", selectedcity);

     
     
  
    
    formData.append(\"imgforsell\",this.state.imgforsell)
    /*const newImageUri = \"file:///\" + imgforsell.split(\"file:/\").join(\"\");

    

    formData.append(\'imgforsell\', {
      uri: newImageUri,
      //uri:`${fileToUpload.fieldname}-${Date.now()}${path.extname(fileToUpload.originalname)}`,
      type: mime.getType(newImageUri),
      name: newImageUri.split(\"/\").pop()
    }

    )*/


      // from stack overflow

  


      
     

/*
     fetch(
        `http://${
          Platform.OS === \"android\" ? ` 192.168.88.45 `: `localhost`
        }:4000/pets/addpets`,
       // \'http://192.168.88.45:4000/pets/addpets/\',
        formData,
        
        //\'http://10.0.2.2:4040/pets/addpets/\',
       //formData,
       
        {
          method: \'POST\',
          //body: JSON.stringify(formData),
          body:formData,
          mode: \'cors\',
         headers: {
          //Accept: \'application/json\',
         //\"content-Type\": `multipart/form-data; boundary={formData._boundary}`,
         \'Content-Type\':\'multipart/form-data;\'
      },
      //body:QueryString.stringify(formData)
          
          
         // headers:{\"Content-type\":\"application/json\"}
        }

       
      )
        .then((res) => {
          if (!res.ok) {
            return Promise.reject(res);
          }
          return res.json();
        })
        .then((data) => {
          console.log(data);
        })
        .catch((err) => {
          console.error(err);
        })
        .finally(() => {
          this.setState({
            name: \"\",
            title: \"\",
            contact: \"\",
            price: \"\",
            description: \"\",
            selectedcat: \"\",
            selectedcity: \"\",
            imgforsell: \"\",
          });
        });
*/
      
    
    /*    axios
  .post(
   // `http://${
    //  Platform.OS === \"android\" ? \"192.168.88.45\" : \"localhost\"
    //}:4000/pets/addpets`,
    //formData,
    `http://192.168.88.45:4000/pets/addpets`, formData
    
 

    
  )
  .then(({ data }) => {
    console.log(data);
  })
  .catch((err) => {
    console.error(err.toJSON());
    // res.status(500).json(err) ???? don\'t do this, it\'s not Express
  })
  .finally(() => {
    this.setState({
      name: \"\",
      title: \"\",
      contact: \"\",
      price: \"\",
      description: \"\",
      selectedcat: \"\",
      selectedcity: \"\",
      imgforsell: \"\",
    });
  });*/

   await axios({
    method: \"post\",
    //url: \"http://192.168.88.45:4000/pets/addpets\",
   url:\'http://10.0.2.2:4000/pets/addpets\',
    data: JSON.stringify(formData),
    headers: { 
      
     // \"Content-Type\": `multipart/form-data`,
     //\'content-type\': \'application/x-www-form-urlencoded\'
     \"Content-Type\" : \"application/json\"
      
  
  
  },
  })
    .then(function (response) {
      //handle success
      console.log(response);
    })
    .catch(function (response) {
      //handle error
      console.log(response);
    });
    this.setState({
      name: \"\",
      title: \"\",
      contact: \"\",
      price: \"\",
      description: \"\",
      selectedcat:\"\",
      selectedcity:\"\",
      imgforsell:\"\"
    });

  };  
//}

  

  

  render() {
   
    const {imgforsell} = this.state
    
  
   
    return (

      
      <View>
      <ScrollView
        nestedScrollEnabled={true}
        showsVerticalScrollIndicator={false}
      >
        <View style={styles.container}>
          <View style={styles.formContainer}>
            <Text style={styles.conText}>Please Fill the Below Form </Text>

            <View style={styles.borderForm}>
              <Text style={styles.formText}>Your Name</Text>
              <TextInput
                style={styles.formInput}
                multiline
                placeholder=\"Please Enter Your Name\"
                maxLength={15}
                value={this.state.name}
                onChange={this.onChangePetName}
                blurOnSubmit={true}
                onChangeText={(name) => this.setState({ name })}
              />

              <Text style={styles.formText}>Category</Text>

             { /*<CategoryDropList />*/ }

             <View style={styles.viewStyle}>
            
             <Picker
          
           itemStyle={styles.itemStyle}
            mode=\"dropdown\"
           style={styles.pickerStyle}
            selectedValue={this.state.selectedcat}
           // onValueChange={this.onValueChangeCat.bind(this)}
           //onValueChange={(selectedcat)=>this.setState({selectedcat})}
           onValueChange={(itemValue,itemIndex)=> this.setState({selectedcat:itemValue})}
        
          >
            {this.state.category.map((item, index) => (
              <Picker.Item
               
                color=\"black\"
                label={item.itemName}
                value={item.itemName}
                index={index}
              />
            ))}
          </Picker>
         
          </View>

              

              <Text style={styles.formText}>Pet/Product Title</Text>
              <TextInput
                style={styles.formInput}
                placeholder=\"Enter Product Title\"
                maxLength={15}
                value={this.state.title}
                blurOnSubmit={true}
                onChange={this.onChangePetTitle}
                onChangeText={(title) => this.setState({ title })}
              />

              <Text style={styles.formText}>City</Text>

              {/*<CityDropList />*/}

              <View style={styles.viewStyle}>

              <Picker
          
           itemStyle={styles.itemStyle}
            mode=\"dropdown\"
           style={styles.pickerStyle}
            selectedValue={this.state.selectedcity}
           onValueChange={(itemValue,itemIndex)=> this.setState({selectedcity:itemValue})}
        
          >
            {this.state.cityCategory.map((item, index) => (
              <Picker.Item
               
                color=\"black\"
                label={item.itemName}
                value={item.itemName}
                index={index}
              />
            ))}
          </Picker>

          

          </View>
              <Text style={styles.formText}> Contact Number </Text>
              <TextInput
                style={styles.formInput}
                placeholder=\"Phone Number\"
                inputType=\"number\"
                maxLength={11}
                keyboardType=\"number-pad\"
                blurOnSubmit={true}
                value={this.state.contact}
                onChange={this.onChangePetContact}
                onChangeText={(contact) => this.setState({ contact })}
              />
              <Text style={styles.formText}>Price</Text>
              <TextInput
                style={styles.formInput}
                multiline
                placeholder=\"Enter Price\"
                inputType=\"number\"
                keyboardType=\"number-pad\"
                blurOnSubmit={true}
                maxLength={7}
                value={this.state.price}
                onChange={this.onChangePetPrice}
                onChangeText={(price) => this.setState({ price })}
              />
              <Text style={styles.formText}>Image of Product</Text>

              {/*<ImagePickerExample />*/}

             

              <TouchableOpacity id=\"fileinput\" style={styles.btn} onPress={this._getPhotoLibrary.bind(this)}>
              <Text style={styles.btnTxt}> Choose File</Text> 
                </TouchableOpacity>
        
                {imgforsell ? (
              <Image source={{ uri: imgforsell.uri }} style={styles.uploadimgstyle} />
            ) : (
              <View/>
            )}
            
              
              <Text style={styles.formText}>
                Description(Optional max 150 words)
              </Text>
              <TextInput
                style={styles.descriptionInput}
                multiline
                placeholder=\"Describe your product\"
                maxLength={150}
                blurOnSubmit={true}
                value={this.state.description}
                onChange={this.onChangePetDescription}
                onChangeText={(description) => this.setState({ description })}
              />
              <TouchableOpacity style={styles.btn} onPress={this.onSubmit}>
                <Text style={styles.btnTxt}>Submit</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </ScrollView>
      </View>
     
    );
  }
}



路由.js


// Importing important packages
const express = require(\"express\");

const sharp = require(\'sharp\');
bodyParser = require(\"body-parser\");


//const RNFS = require(\'react-native-fs\');

// Using express and routes
const app = express();
const petRoute = express.Router();


//Import multer
const multer = require(\"multer\");

//file system
const fs = require(\"fs\");

//path
path = require(\"path\");

//moongoose
const mongoose = require(\'mongoose\');
const petModel = require(\"../Models/PetsSell\");

// pet module which is required and imported
  //petModel = require(\"../Models/PetsSell\");
//const { db } = require(\"../Models/PetsSell\");

// To Get List Of pets
petRoute.route(\"/\").get(function (req, res) {
  petModel.find(function (err, pet) {
    if (err) {
      console.log(err);
    } else {
      res.json(pet);
    }
  });
});

// Multer
//geeksforgeeks code {/*https://www.geeksforgeeks.org/upload-and-retrieve-image-on-mongodb-using-mongoose/#:~:text=So%20for%20storing%20an%20image,in%20the%20form%20of%20arrays.*/}
/*

petRoute.route(\'/addpets\').post( upload.single(\'imgforsell\'), (req, res, next) => {
  
    var obj = {
        name: req.body.name,
        title: req.body.title,
        contact: req.body.contact,
        price: req.body.price,
        description: req.body.description,
        selectedcat: req.body.selectedcat,
        selectedcity: req.body.selectedcity,
        imgforsell: {
            data: fs.readFileSync(path.join(__dirname + \'./Upload/Images/\' + req.file.filename)),
            contentType: \'image/jpg\'
        }
    }
    petModel.save(obj, (err, item) => {
        if (err) {
            console.log(err);
        }
        else {
            // item.save();
            res.redirect(\'/addpets\');
        }
    });
});

*/

// Updating Multer

/*

const storage = multer.diskStorage({
  destination: \"./Upload/Images\",
  filename: (req, file, cb) => {
    return cb(
      null,
      //file.originalname
    `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
     //`${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`
    
    );
  },
});

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 900000,
  },
});*/


/*var dir = \"../Upload/Images\";
var upload = multer({
  storage: multer.diskStorage({
    destination: function (req, file, callback) {
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
      }
      callback(null, \"../Upload/Images\");
    },
    filename: function (req, file, callback) {
      callback(
        null,
        file.fieldname + \"-\" + Date.now() + path.extname(file.originalname)
      );
    },
  }),

  fileFilter: function (req, file, callback) {
    var ext = path.extname(file.originalname);
    if (ext !== \".png\" && ext !== \".jpg\" && ext !== \".jpeg\") {
      return callback(//res.end(\'Only images are allowed\')
       null, false);
    }
    callback(null, true);
  },
});*/

{/* From here Changing code to string type data base  */ }
/*app.post( \'/pets/addpets\',upload.single(\'imgforsell\'), (req, res) => {
  try {
    if (
      req.file &&
      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.file.originalname;
      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,
    });
  }




});*/





{/* Previous Code to add Pets */}


const storage = multer.diskStorage({
  destination: \"./Upload/Images\",
  filename: (req, file, cb) => {
    return cb(
      null,
      //file.originalname
     // path=\'../Upload/Images/\',
    `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
     //`${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`
    
    );
  },
});


const upload = multer({
  storage: storage,
  limits: {
    fileSize: 900000,
  },
});

petRoute.route(\"/addpets\").post(upload.single(\"imgforsell\"),  (req, res) => {
    
    
console.log(req.file);

  var img = fs.readFileSync(req.file.path);


 //var img = fs.readFileSync(req.body.path);
 var encode_image = img.toString(\"base64\");
 
  
  const pet = new petModel({
    name: req.body.name,
    title: req.body.title,
    contact: req.body.contact,
    price: req.body.price,
    description: req.body.description,
    selectedcat: req.body.selectedcat,
    selectedcity: req.body.selectedcity,
    imgforsell: Buffer.from(encode_image, \"base64\"),
   //imgforsell:req.body.imgforsell,
   contentType: req.file.mimetype,
    //contentType: multipart/form-data
    
  });

   pet
    .save()// img
    .then((img) => {
      //img.id
       res.json(img.id);
     
    })
    .catch((err) => {
      //remove return and curly braces
  return res.json(err)});
    
});


/*petRoute.route(\"/pets/addpets\").post(upload.single(\"imgforsell\"),  (req, res) => {
    
    
console.log(req.file);

 var img = fs.readFileSync(req.file.path);

 //var img = `${RNFS.DocumentDirectoryPath}//${new Date().toISOString()}.jpg`.replace(/:/g, \'-\');

 {/*var img = `${fs.DocumentDirectoryPath}//${new Date().toString()}.jpg`.replace(`/g`, \'-\')

 if(Platform.OS === \'ios\') {
 // console.log(path, dest);
  fs.copyAssetsFileIOS(response.origURL, img, 0, 0)
      .then(res => {})
      .catch(err => {
          console.log(\'ERROR: image file write failed!!!\');
          console.log(err.message, err.code);
      });
} else if(Platform.OS === \'android\') {
  //console.log(path, dest);
  fs.copyFile(response.uri, img)
      .then(res => {})
      .catch(err => {
          console.log(\'ERROR: image file write failed!!!\');
          console.log(err.message, err.code);
      });
}
// here was comment star and slash please add

 //var img = fs.readFileSync(req.body.path);
 var encode_image = img.toString(\"base64\");
 
  
  const pet = new petModel({
    name: req.body.name,
    title: req.body.title,
    contact: req.body.contact,
    price: req.body.price,
    description: req.body.description,
    selectedcat: req.body.selectedcat,
    selectedcity: req.body.selectedcity,
    imgforsell: Buffer.from(encode_image, \"base64\"),
   //imgforsell:req.body.imgforsell,
    contentType: req.file.mimetype,
    
  });

   pet
    .save(img)// img
    .then((img) => {
      //img.id
       res.json(img.id);
     
    })
    .catch((err) => {
      //remove return and curly braces
  return res.json(err)});
    
});*/

petRoute.route(\"/pets/addpets\").get((req, res) => {
 var filename = req.params.id;

  petModel.findOne(
    { _id: mongoose.Types.ObjectId(filename) },
    (err, result) => {
      if (err) return console.log(err);
      console.log(result);

      res.contentType(result.contentType);
      res.send(new Buffer.from(result.imgforsell.buffer, \"base64\"));
    }
  );
  
  
 

}

);

// To Add New pet

/*petRoute.route(\'/addpets\').post(function (req, res) {
let pet = new petModel(req.body);
pet.save()
.then(game => {
res.status(200).json({ \'pets\': \' Added Pets\' });
})
.catch(err => {
res.status(400).send(\"Something Went Wrong\");
});
});*/

// To Get pet Details By pet ID

/*petRoute.route(\'/editPets/:id\').get(function (req, res) {
let id = req.params.id;
petModel.findById(id, function (err, pet) {
res.json(pet);
});
});*/

// To Update The pet Details
/*
petRoute.route(\'/updatePets/:id\').post(function (req, res) {
petModel.findById(req.params.id, function (err, pet) {
if (!pet)
return next(new Error(\'Unable To Find Pets With This Id\'));
else {
pet.name = req.body.name;
pet.title = req.body.title;
pet.contact = req.body.contact;

pet.save().then(emp => {
res.json(\'Pets Updated Successfully\');
})
.catch(err => {
res.status(400).send(\"Unable To Update Pets\");
});
}
});
});*/

// To Delete The pet
/*
petRoute.route(\'/deletePets/:id\').get(function (req, res) {
petModel.findByIdAndRemove({ _id: req.params.id }, function (err, pet) {
if (err) res.json(err);
else res.json(\'pet Deleted Successfully\');
});
});*/

module.exports = petRoute;


服务器.js


// Imported required packages
const express = require(\'express\'),
path = require(\'path\'),
bodyParser = require(\'body-parser\'),
cors = require(\'cors\'),
mongoose = require(\'mongoose\');
var cors_proxy = require(\'cors-anywhere\');

// MongoDB Databse url
var mongoDatabase = \'mongodb://localhost:27017/PetsBazar\';

// Created express server
const app = express();
mongoose.Promise = global.Promise;

// Connect Mongodb Database
mongoose.connect(mongoDatabase, { useNewUrlParser: true }).then(
() => { console.log(\'Database is connected\') },
err => { console.log(\'There is problem while connecting database \' + err) }
);

// All the express routes
const petRoutes = require(\'./Routes/PetsSell.Routes\');

// Conver incoming data to JSON format
app.use(bodyParser.json());
app.use(
   bodyParser.urlencoded({      // to support URL-encoded bodies
      extended: false,
    })
  );

// Enabled CORS
app.use(cors());
app.use(express.static(\"./Upload/Images\"));



// Setup for the server port number
const port = process.env.PORT || 4000;


// Routes Configuration
app.use(\'/pets\', petRoutes);

app.use(function(req, res, next) {
  res.header(\"Access-Control-Allow-Origin\", \"192.168.88.45:4000\"); // update to match the domain you will make the request from
  res.header(\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept\");
  next();
});

// Staring our express server


const server = app.listen(port, function () {
console.log(\'Server Lisening On Port : \' + port);
});
/*cors_proxy.createServer({
  originWhitelist: [], // Allow all origins
  requireHeader: [\'origin\', \'x-requested-with\'],
  removeHeaders: [\'cookie\', \'cookie2\']
}).listen(port, \'192.168.88.45\',  function() {
  console.log(\'Running CORS Anywhere on \'  + \':\' + port);
});
*/



    标签: node.js react-native multer


    【解决方案1】:

    您可以在后端添加此行

    app.use(express.bodyParser({limit: '50mb'}));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-16
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-09
      • 2018-06-19
      • 1970-01-01
      相关资源
      最近更新 更多