1

Im trying to impl CRUD operations using React.js, Express.js and Node so I write a basic code and thats working but I wanna use Model and Controller to have a clean code so thats not working and send me error I don't know what the problem is so can someone here guide me to make it works please. by the way the Get works but for insert no.

I test it with postman and I get:

Error : Cannot POST /api/insert

Here is the code :

Controller.js

// create new car   
exports.createNewCar = (req, res) =>{
    const carReqData = new CarModel(request.body);
    console.log('carReqData', carReqData);
    // check null
    if(req.body === Object && Object.keys(req.body).length === 0){
        res.send(400).send({success: false, message: 'Please fill all fields'});
    }else{
        CarModel.createCar(carReqData, (err, car)=>{
            if(err)
            res.send(err);
            res.json({status: true, message: 'Car Created Successfully', data: car.insertId})
        })
    }
}

Model.js

// create new car
var Car = function(car){
    this.idCars = car.idCars;
    this.carName = car.carName;
    this.carModel = car.carModel;
}
Car.createCar = (carReqData, result) =>{
    db.query('INSERT INTO Cars SET ?', carReqData, (err, res)=>{
        if(err){
            console.log('Error while inserting data');
            result(null, err);
        }else{
            console.log('Car created successfully');
            result(null, res)
        }
    })
}

Routes.js

// create new car
router.post('/insert', carController.createNewCar);

Index.js

app.use('/insert', CarRoutes);
2
  • Your POST route error is returning a prefix of '/api', so check your router definition, see here for how to prefix routes, might give you something to look for: stackoverflow.com/questions/68910733/… Commented Aug 24, 2021 at 16:25
  • @ConBran Yeah I should add /api to route of post... Thank you Commented Aug 24, 2021 at 16:48

1 Answer 1

1

I fix the issue by editing the route

Routes.js

router.post('/', carController.createNewCar);

index.js

app.use('/app/insert', CarRoutes);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.