Saturday 6 May 2017

Client side routing using jQuery/JavaScript

I'm doing some experimenting in using pure JS/jQuery to handle client-side logic (rather than a framework, like Angular). The problem I'm running into right now is how to log a user in.

Here is my login.hbs file:

<div align="center">
<h2 class="page-header">Account Login</h2>
<form>
  <div class="form-group">
    
    <input type="text" class="form-control" name="username" placeholder="Username" style="width: 20%">
  </div>
  <div class="form-group">
    
    <input type="password" class="form-control" name="password" placeholder="Password" style="width: 20%">
  </div>
  <button type="button" class="btn btn-success" onclick="login()">Login</button>
</form>
</div>

This submit request goes to a JS file: login.js:

$(document).ready(function() {
    login = () => {     
        var username = $("[name='username']").val()
        var password = $("[name='password']").val()
        $.ajax({
            type: "PUT",
            url: '/login',
            data: {
                username: username,
                password: password
            },
            success: function(response) {
                console.log('Success:')
                console.log(response)
            },
            error: function(error) {
                console.log("Error:")
                console.log(error)
            }
        })
    }
})

On the server side, I'm accepting this PUT request in index.js:

router.put('/login', function(req, res) {
    // Password is not encrypted here
    console.log('req.body')
    console.log(req.body)

    User.findOne({ username: req.body.username }, function(err, user) {
        // Password is encrypted here
        if (err) throw err
        console.log('user')
        console.log(user)

        bcrypt.compare(req.body.password, user.password, function(err, result) {
            if (result) {
                var token = jwt.encode(user, JWT_SECRET)
                return res.status(200).send({ user: user, token: token })
            } else {
                return res.status(401).send({error: "Something is wrong."})
            }
        })
    })
})

The current flow is: a user enters their credentials, and those credentials get returned to the success method in my ajax request. The credentials show up in the browser's console (confirming that the server and client are communicating). The question is, how do I route this request to the profile page (or any other page, for that matter)? That is, the user is at http://localhost:3000/login, and after successfully logging in, they are routed to http://localhost:3000/profile, for example, where their personal profile information appears. I'd love to learn both ways of doing this type of routing (server-side and client-side). Thanks!



via Farid

No comments:

Post a Comment