Full-Stack Web Development with Vue.js and Node

(singke) #1
Building Authentication with passport.js Chapter 6

},
},
};
</script>

If you are familiar with ajax, you should be able to quickly understand the code. If not,


don't worry, it's actually quite simple. The axios method takes important parameters, such


as the request method (in preceding case, post), the data parameters or the payloads, and


a URL endpoint to hit. It takes these parameters and routes them to either the then()


method or catch() method depending on the server's response.


If the request is successful, it goes to the then() method; if not, it goes to the catch()


method. Now, the success and failure of the requests are also customizable according to our
needs. For the preceding scenario, we will simply pass an error response if the user is not


saved to the database. We can also do it for the validations.


So, let's also modify users.js inside the controller method to accommodate these


changes:


const User = require('../models/User.js');

module.exports.controller = (app) => {
// register a user
app.post('/users/register', (req, res) => {
const name = req.body.name;
const email = req.body.email;
const password = req.body.password;
const newUser = new User({
name,
email,
password,
});
User.createUser(newUser, (error, user) => {
if (error) {
res.status(422).json({
message: 'Something went wrong. Please try again after some
time!',
});
}
res.send({ user });
});
});
};
Free download pdf