import User from '../model/user.js';
// Get all users
export const getUsers = async (request, response) => {
// Step -1 // Test API
// response.send('Code for Interview');
try{
// finding something inside a model is time taking, so we need to add await
const users = await User.find();
return response.status(200).json(users);
}catch( error ){
return response.status(404).json({ message: error.message })
}
}
// Save data of the user in database
export const addUser = async (request, response) => {
// retreive the info of user from frontend
const user = request.body;
response.send("hello");
const newUser = new User(user);
try{
await newUser.save();
response.status(201).json(newUser);
} catch (error){
return response.status(404).json({ message: error.message});
}
}
// Get a user by id
export const getUserById = async (request, response) => {
try{
const user = await User.findById(request.params.id);
response.status(200).json(user);
}catch( error ){
response.status(409).json({ message: error.message })
}
}
// Save data of edited user in the database
export const editUser = async (request, response) => {
let user = await User.findById(request.params.id);
user = request.body;
const editUser = new User(user);
try{
await User.updateOne({_id: request.params.id}, editUser);
response.status(201).json(editUser);
} catch (error){
return response.status(411).json({ message: error.message});
}
}
// deleting data of user from the database
export const deleteUser = async (request, response) => {
try{
await User.deleteOne({_id: request.params.id});
response.status(201).json("User deleted Successfully");
} catch (error){
response.status(406).json({ message: error.message});
}
}
This is the error I am receiving
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:371:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (C:UserseggfrDesktopdemocrud-servicenode_modulesexpresslibresponse.js:771:10)
at ServerResponse.send (C:UserseggfrDesktopdemocrud-servicenode_modulesexpresslibresponse.js:170:12)
at ServerResponse.json (C:UserseggfrDesktopdemocrud-servicenode_modulesexpresslibresponse.js:267:15)
at addUser (file:///C:/Users/eggfr/Desktop/demo/crud-service/controller/user-controller.js:29:37)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: