Hi all, I’ve recently added my script to include a POST method as before it only had a get and was issuing a CANNOT POST /update-user issue. The error no longer appears but now when I edit existing information on the form it does not update.
This is my route.js file
const express = require('express');
const route = express.Router();
const services = require('../services/render');
const controller = require('../controller/controller');
/* @descript Root Route
@method GET/
*/
route.get('/',services.homeRoutes);
/* @descript add users
@method GET/ add-user
*/
route.get('/add-user', services.add_user);
/* @descript update users
@method GET/ update-user
*/
//extra
route.post('/update-user', services.update_user);
route.get('/update-user', services.update_user);
//API
route.post('/api/users', controller.create);
route.get('/api/users', controller.find);
route.put('/api/users/:id', controller.update);
route.delete('/api/users/:id', controller.delete);
module.exports=route;
The next is my section on the render.js on the update-user part
exports.update_user = (req,res) =>{
axios.get('http://localhost:3000/api/users',{params:{id: req.query.id}})
.then(function(userdata){
res.render('update_user',{user : userdata.data});
})
.catch(err =>{
res.send(err);
});
};
This is the other update user part for my controller.js script
//Update a new identified user by user id
exports.update = (req, res) => {
if(!req.body){
return res.status(400).send({
message:"data to update content can not be empty"
});
}
const id = req.params.id;
Userdb.findByIdAndUpdate(id, req.body,{ useFindAndModify: false})
.then(data=>{
if(!data){
res.status(404).send({
message:"User not found with id${id} "
});
}else
{
res.send(data);
}
});
};
and this is my index.js with update-user
$("update_user").submit(function(event){
event.preventDefault();
var unindexed_array = $(this).serializeArray();
var data = {}
$.map(unindexed_array,function(n, i){
data[n['name']] = n['value']
})
var request = {
"url":'http://localhost:3000/api/users/${data.id}',
"method": "PUT",
"data":data
};
$.ajax(request).done(function(response){
alert("Data Updated Successfully!");
});
});
I am not sure what is wrong. Before it was the POST method but adding it to the router.js made the error disappear. But now, it is not updating user information by ID. I am using Mongoose library for this.