简体   繁体   中英

Express nodejs not inserting data using mongoose with form-data

From last 2 weeks i am unable to post a data to insert into database using form-data it always shows 400 bad request here is my code My server.js

 require('./db.js') let express = require('express') // let mongoose = require() const app = express() const path = require('path') let routes = require('./routes'); const bodyParser = require('body-parser') app.set('port', 4000); // app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended:false})) app.use('/api', routes); app.use(function(req, res, next){ console.log(req.method, req.url); next(); }) let server = app.listen(app.get('port'), function(){ let port = server.address().port; console.log("Connected Successfully at", + port); }); 
here is my Controller file code

 let mongoose = require('mongoose'); let cat = mongoose.model('Cat') module.exports.addcat = function(req, res){ console.log(req.body); cat. create({ cat_name: req.body.cat_name, cat_description: req.body.cat_description },function(err, cate){ if(err){ console.log(" Error creating Hotel"); res .status(400) .json(err) }else{ console.log("Hotel created", cate); res .status(200) .json(cate); } }) } 

Here is my schema file shop.models.js

 let mongoose = require('mongoose') let productSchema = new mongoose.Schema({ prod_name : { type:String, required:true }, prod_description : { type:String, required:true }, prod_base_price : { type:Number, required:true }, prod_tax : { type:Number, required:true }, prod_final_price : { type:Number, required:true }, prod_images : [Array], prod_discount : { type:Number, required:true } }) let catSchema = new mongoose.Schema({ cat_name:{ type:String, required:true }, cat_description:{ type:String, required:true } }) mongoose.model("Cat", catSchema); 

this my routes file routes.js

 const express = require('express') const router = express.Router(); const ctrlCat = require('../controllers/cat.controller.js') // Category Router router .route('/cat') .get(ctrlCat.getcat) .post(ctrlCat.addcat); router .route('/cat/:catid') .get(ctrlCat.getonecat) .put(ctrlCat.editonecat) .delete(ctrlCat.deletecat); module.exports = router; 

Please help me to out always shows this error

 { "errors": { "cat_name": { "message": "Path `cat_name` is required.", "name": "ValidatorError", "properties": { "message": "Path `{PATH}` is required.", "type": "required", "path": "cat_name" }, "kind": "required", "path": "cat_name", "$isValidatorError": true }, "cat_description": { "message": "Path `cat_description` is required.", "name": "ValidatorError", "properties": { "message": "Path `{PATH}` is required.", "type": "required", "path": "cat_description" }, "kind": "required", "path": "cat_description", "$isValidatorError": true } }, "_message": "Cat validation failed", "message": "Cat validation failed: cat_name: Path `cat_name` is required., cat_description: Path `cat_description` is required.", "name": "ValidationError" } 

and 400 bad request i am unable to understand where m doing wrong please help me out m stuck here from last 2 weeks When ever i send my data using form-data it show this error other wise it working fine with urlencoded and raw. Currently m testing over postman. I tried this with react too but shows same issue

you need to use appropriate middleware to parse the form data, so that req.body will contain the form data. So uncommenting

app.use(bodyParser.json());

should do the trick.

Furthermore you should export your cat schema.

module.exports = mongoose.model("Cat", catSchema);

and require in the control file using.

const cat = require( ' /path/to/cat ' );

It appears that json response after saving the new cat object somehow produces extra character. You can try manually editing it out. Somewhat like this

module.exports.addcat = function(req, res){
console.log(req.body);
cat.
    create({
    cat_name: req.body.cat_name,
    cat_description: req.body.cat_description

},function(err, cate){
    if(err){
        console.log(" Error creating Hotel");
        res
            .status(400)
            .json(err)
    }else{
        console.log("Hotel created", cate);
            //manual editing
            var firstChar = cate.substring(0, 1);
            var firstCharCode = cate.charCodeAt(0);
            if (firstCharCode == 65279) {
                console.log('First character "' + firstChar + '" (character code: ' + firstCharCode + ') is invalid so removing it.');
                cate = cate.substring(1);
            }

            var parsedJson = JSON.parse(cate);
            console.log('parsedJson: ', parsedJson);
            res
                .status(200)
                .json(cate);
    }
})
}

If the same issue appears some where else then use this there too. Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM