5. Registration

In this chapter, we will add the register feature to our app. First, we will be creating an API that will receive the values from the client and insert them into our Mongo DB. Then we will create a component in our Vue JS app that will display the registration form and call an AJAX to the server when that form submits.

Video tutorial:

Create a new file named “RegisterComponent.vue” in your components folder.

Then in your main.js file register this component with the “/register” route:

import RegisterComponent from "./components/RegisterComponent.vue"

const routes = [
    ...
    
    { path: '/register', component: RegisterComponent },
];

Then in your RegisterComponent.vue file, write the following code:

<template>
    <div class="container" style="margin-top: 50px;">
        <div class="row">
            <div class="offset-md-3 col-md-6">
                <form method="POST">
                    <div class="form-group">
                        <label class="text-white">Enter name</label>
                        <input type="text" class="form-control" name="name" />
                    </div>

                    <br />

                    <div class="form-group">
                        <label class="text-white">Enter email</label>
                        <input type="email" class="form-control" name="email" />
                    </div>

                    <br />

                    <div class="form-group">
                        <label class="text-white">Enter password</label>
                        <input type="password" class="form-control" name="password" />
                    </div>

                    <br />

                    <input type="submit" value="Register" name="submit" class="btn btn-primary" />
                </form>
            </div>
        </div>
    </div>
</template>

<script>

    export default {
        //
    }
</script>

If you check the browser now, you will see a registration form.

register
register

Nothing happens when you submit the form now because we need to attach an event listener and create an API for it.

Submitting the Form

Then in your <form> tag, attach an onsubmit event listener that will be called when the form submits.

<form method="POST" v-on:submit.prevent="doRegister">

We are using “prevent” so it will prevent the form from reloading the page. We will create this function in a moment.

Also, replace the input type submit with the following:

<input type="submit" v-bind:value="isLoading ? 'Loading...' : 'Register'" v-bind:disabled="isLoading" name="submit" class="btn btn-primary" />

We will display the text “Loading…” when the AJAX is called, and “Register” when the response is received from the server. Also, we will disable the submit button when the form is submitted once, and enable it again when the response is received.

Then you need to install a module named “axios” that will be used to call AJAX requests. We also need to install a module named “sweetalert2” that will be used to display pop-up alerts.

> npm install axios sweetalert2

Then you need to include them in your <script> tag:

import axios from "axios"
import swal from "sweetalert2"

Then add the following lines in your “main.js” after the app object is initialized:

app.config.globalProperties.$mainURL = "http://localhost:8080"
app.config.globalProperties.$apiURL = "http://localhost:3000"

Coming back to your RegisterComponent.vue file and replace the export default object with the following:

export default {
    data() {
        return {
            "isLoading": false
        }
    },

    methods: {
        doRegister: async function () {
            const form = event.target;
            const formData = new FormData(form);

            this.isLoading = true;

            const response = await axios.post(
                this.$apiURL + "/registration",
                formData
            );
            
            this.isLoading = false;
            swal.fire("Success", response.data.message, "success");

            if (response.data.status == "success") {
                form.reset();
            }
        }
    }
}

Check the app now, you will see no change in the output. But if you fill the form now and hit the submit button, you will see the submit button gets disabled and its text changed to “Loading…”.

You will also see errors in your browser console that says “No ‘Access-Control-Allow-Origin’ header is present on the requested resource”.

register cors
register cors

CORS Origin Headers

Then you need to add the headers in your “api/server.js” file. Open your server.js file and add the following lines to it:

// Add headers before the routes are defined
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Authorization');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

Refresh the page now and fill the form again and hit submit. Now you will not see a CORS header error, but you will see a 404 error. That is because you need to create an API for it in your server file.

register 404
register 404

express-formidable

To receive the values from AJAX in the Node JS express server, we are going to use a module named express-formidable. So simply run the following command in your CMD opened in api folder:

> npm install express-formidable

After that, open your server.js file and write the following 2 lines before starting the HTTP server:

// module required for parsing FormData values
const expressFormidable = require("express-formidable");

// setting the middleware
app.use(expressFormidable());

This will tell the server that we will be using this module to parse the incoming values from input fields and files.

bcrypt

This module is used to encrypt the plain text into a hash. We will be using this for saving the user’s password in the encrypted hash. This library also provides a method to verify the plain text against the encrypted hash, so we can use it while login in.

Run the following command to install this module in your project:

> npm install bcrypt

Then you need to include it in your server file:

// module required for encrypting the passwords
// and verify the password as well
const bcrypt = require("bcrypt");

Now we can use this module’s functions in your server.js file.

Saving User’s data in Mongo DB

Our all routes go in the mongo DB connection callback. So, create the following POST route in your server file:

// connect with database
MongoClient.connect("mongodb://localhost:27017", function (error, client) {
    ...
    console.log("Database connected");

    app.post("/registration", async function (request, result) {
        const name = request.fields.name;
        const email = request.fields.email;
        const password = request.fields.password;
        const createdAt = new Date().getTime();

        if (!name || !email || !password) {
            result.json({
                status: "error",
                message: "Please enter all values."
            });
            return;
        }

        // check if email already exists
        var user = await db.collection("users").findOne({
            email: email
        });

        if (user != null) {
            result.json({
                status: "error",
                message: "Email already exists."
            });
            return;
        }

        // encrypt the password
        bcrypt.hash(password, 10, async function (error, hash) {

            // insert in database
            await db.collection("users").insertOne({
                name: name,
                email: email,
                password: hash,
                accessToken: "",
                contacts: [],
                createdAt: createdAt
            });

            result.status(200).json({
                status: "success",
                message: "User has been signed up."
            });
        });
    });
});

Run the app now, fill out the registration form, and hit submit. First, you will see an alert dialog that the user has been signed up.

register success
register success

And if you check your database from Mongo DB Compass, you will see a new document created inside the user’s collection.

user mongodb
user MongoDB

You might have to refresh the database or re-open Mongo DB Compass to see your new database.

So the registration part is done. In the next chapter, we will do the login part.





Please disable your adblocker or whitelist this site!