Execute function in controller from view (EJS NodeJs)

Viewed 410

Expected scenario: Click Create Account button, will execute a function in controllers/user.js, which will do basic form validation, do a RESTful call to create record in MongoDB. Will return message such as validation errors, account exists, or account created successful.

app.js:

/**
 * User Controller.
 * Route to Signup page.
 */
const userController = require('./controllers/user');
app.get('/signup', userController.getSignup);

controllers/user.js

/**
 * GET /signup
 * Signup page.
 */
exports.getSignup = (req, res) => {
  res.render('pages/account/signup', {
    title: 'Create Account',
    clickSignup: clickSignup
  });

  function clickSignup(form) {
     // check form
     // write to Mongo
     if(error){ errorMessage = "error message"; }
  };
};

pages/signup.ejs:

<button onclick="clickSignup()">Create Account</button>
<span class="showErrorMessages"><%= errorMessage %></span>
  1. On the click on that button, I would like to create the user account. What is the best way to do this? How do I create a function in controllers/user.js that can be executed from the view. And display any error messages such as "validation errors" or "account already exists"?

  2. Is this project structure good practice? Or is it better for me to just use a MVC framework such as Angular?

0 Answers
Related