concept create action in category node

appears as: The create action, create action
Get Programming with Node.js

This is an excerpt from Manning's book Get Programming with Node.js.

The new action takes incoming requests to create a new user and render the form in new.ejs. The create action receives incoming posted data from the form in new.ejs and passes the resulting created user to the next middleware function through the response object. The next middleware function, redirectView, determines which view to show based on the redirect path it receives as part of the response object. If a user is created successfully, redirect to the index page.

In the create action, assign a userParams variable to the collected incoming data. Then call User.create and pass those parameters, redirecting the user to the /users index page upon success and to the error page in case of a failure.

24.2. Modifying the create action to use passport registration

Using Passport.js has already simplified your code and made it easier to specify which models you’d like to hash and authenticate. The next step is modifying your create action, so instead of using your bcrypt hashing function before creating a user account, you’ll use Passport.js. By incorporating the Passport.js modules, you have access to a library of methods to streamline the account registration process. Change the create action in usersController.js to use the register method, as shown in listing 24.4.

Listing 24.4. Registering new users in the create action in main.js
create: (req, res, next) => {
  if (req.skip) next();

  let newUser = new User( getUserParams(req.body) );

  User.register(newUser, req.body.password, (error, user) => {   #1
    if (user) {
      req.flash("success", `${user.fullName}'s account created
 successfully!`);
      res.locals.redirect = "/users";
      next();                                                    #2
    } else {
      req.flash("error", `Failed to create user account because:
 ${error.message}.`);
      res.locals.redirect = "/users/new";
      next();                                                    #3
    }
  });
}