Full-Stack React Projects
上QQ阅读APP看书,第一时间看更新

Creating a new user

The API endpoint to create a new user is declared in the following route.

mern-skeleton/server/routes/user.routes.js:

router.route('/api/users').post(userCtrl.create)

When the Express app gets a POST request at '/api/users', it calls the create function defined in the controller.

mern-skeleton/server/controllers/user.controller.js:

const create = (req, res, next) => {
const user = new User(req.body)
user.save((err, result) => {
if (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err)
})
}
res.status(200).json({
message: "Successfully signed up!"
})
})
}

This function creates a new user with the user JSON object received in the POST request from the frontend within req.body. The user.save attempts to save the new user into the database after Mongoose does a validation check on the data, consequently an error or success response is returned to the requesting client.