Struggling to retrieve information from a template and transfer it to a controller in AngularJS

Currently, I am encountering issues with user authentication in my template. Oddly enough, everything works fine when testing with Postman. Firstly, I initiate an API call to /users/authenticate to retrieve a token. Next, I verify the token by making another API call to /users/me. Fortunately, this process is successful in allowing users to log in.

Here's a snippet from my controller:

    .controller('homeCtrl', ['$rootScope', '$location', '$http', '$timeout', 'Auth', function ($rootScope, $location, $http, $timeout, Auth) {
    $rootScope.loadme = false;
    $rootScope.currentPa = $location.path();
    $rootScope.$on('$routeChangeStart', function () {
        if (Auth.isLoggedIn()) {
            console.log('Success: User is logged in');
            $rootScope.isLoggedIn = true;
            Auth.getUser()
                .then(function (data) {
                    $rootScope.username = data.data.username;
                    $rootScope.email = data.data.email;
                    $rootScope.loadme = true;
                });
        } else {
            $rootScope.isLoggedIn = false;
            $rootScope.username = '';
            $rootScope.loadme = true;
        }
    });


    $rootScope.doLogin = function (loginData) {
        $rootScope.loading = true;
        $rootScope.errorMsg = false;
        console.log("TEST LOGIN");

        Auth.doLogin($scope.loginData)
            .then(function (data) {
                console.log('logging in');
                if (data.data.success) {
                    console.log('fgsgsg');
                    $rootScope.loading = false;
                    $rootScope.successMsg = data.data.message + 'Redirecting...';
                    $timeout(function () {
                        console.log('12345');
                        $location.path('/#!/');
                        $rootScope.loginData = '';
                        $rootScope.successMsg = false;
                    }, 2000);
                } else {
                    console.log("no success");
                    $rootScope.loading = false;
                    $rootScope.errorMsg = data.data.message;
                }
            })
    };

Below are the server routes and middleware:

//User Login Route
router.post('/authenticate', function (req, res) {
User.findOne({username: req.body.username})
    .select('username email password')
    .exec(function (err, user) {
        if (err) {
            throw err;
        }

        if (!user) {
            res.json({success: false, message: 'Could not authenticate 
user'});
        } else if (user) {
            if (req.body.password) {
                var validPassword = 
user.comparePassword(req.body.password);
            }
            else {
                res.status(200).json({success: false, message: 'Please 
provide password'})
            }
            if (!validPassword) {
                res.status(200).json({success: false, message: 'Could 
not authenticate password'});
            } else {
                var token = jwt.sign({username: user.username, email: 
user.email}, secret, {expiresIn: '24h'});
                res.status(200).json({success: true, message: 'User 
authenticated', token: token});
            }
        }
        console.log(user);
    });
});


 //Middleware for decoding tokens
router.use(function (req, res, next) {
var token = req.body.token || req.body.query || req.headers['x-access-
token'];

if (token) {
    jwt.verify(token, secret, function (err, decoded) {
        if (err) {
            res.json({success: false, message: 'Token Invalid'})
        } else {
            req.decoded = decoded;
            next();
        }
    });
} else {
    res.json({success: false, message: 'No token provided'});
}
});

router.post('/me', function (req, res) {
   res.send(req.decoded);
});

Lastly, presented below is the template structure:

    <div ng-controller="homeCtrl">
        <form ng-submit="doLogin(loginData)">
            <label>Username:</label>
            <input class="form-control" type="text" name="username" placeholder="please enter username"
                   ng-model="loginData.username">
            <br>
            <label>Email:</label>
            <input class="form-control" type="text" name="email" placeholder="please enter email"
                   ng-model="loginData.email">
            <br>
            <label>Password:</label>
            <input class="form-control" type="password" name="password" placeholder="please enter password"
                   ng-model="loginData.password">
            <br>
            <button class="btn btn-primary" type="submit" formmethod="post">Login</button>
        </form>

Answer №1

To improve your dologin function, there is no requirement to pass loginData as a parameter. You can easily enhance the functionality by adding the line $scope.loginData = {}; within your controller. Then, you can test if the data is successfully logged onto the console by printing it within the doLogin() method when it is invoked.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble getting the JavaScript slider to animate

My code works perfectly in Codepen but when I try to implement it on my website, it shows as a static image. You can view the code here: https://codepen.io/anon/pen/zPMKpv I'm using the exact same code on my website located at: Does anyone have any ...

Troubleshooting a Custom Pipe Problem in Angular Material Drag and Drop

Currently, I am working on a project involving Angular Material Drag And Drop functionality. I have created a simplified example on StackBlitz which you can access through this link: here The project involves two lists - one containing pets and the other ...

Error: Unable to access attributes of null object (specifically 'accessToken')

After following a YouTube tutorial by Lama for creating an E-commerce application, I attempted to add a logout feature on the admin page that was not covered in the tutorial. To implement this, I used Redux to grab the currentUser and set it to null to suc ...

A guide on incorporating user input and output in Javascript using React and Material UI

Currently, I am working on a project that requires ReactJS and Material UI. My main goal is to implement the code provided below in just a single JS file. Is there a way to modify this code to meet my formatting requirements? //js file function calculat ...

Creating a Dynamic Bootstrap 4 Dropdown Menu using Jquery Hover

My Bootstrap Dropdown menu has a JQuery animation that is exactly what I want. However, when I move my cursor from the Dropdown's name (.dropdown) to an item in the dropdown, it starts acting erratically. $('.dropdown').hover(function() { ...

Angular's route resolve feature does not wait for the promise to resolve before

I just started using angular and I'm facing an issue with my user route. I'm trying to resolve the user object before rendering the view, but even after injecting $q and deferring the promise, the view is loading before the promise gets returned. ...

Tips for handling numerous usernames in Express JS?

For the past few weeks, I have been diligently working on developing a real-time chat application. Initially, I chose PHP as my back-end language, but I found myself uncomfortable with it and eventually made the switch to Node.js using ExpressJS. However, ...

using a practical example of CORS in JavaScript

I attempted a cross-origin AJAX request (CORS) and stumbled upon this helpful example by MJHALL to get me started. Executing the example on our internal networks (2 separate domains) resulted in success, returning the desired outcome. However, when I inte ...

Guide on transforming complex nested JSON into CSV format using jq for easy conversion back and forth

How can I utilize jq to convert any random JSON array of objects into CSV, even when the objects in the array are deeply nested? While StackOverflow offers numerous solutions for specific input or output fields, I am looking for a universal solution that ...

Identify data points on the line chart that fall outside the specified range with ng2-charts

I'm struggling to figure out how to highlight specific points on a line chart that fall outside a certain range. For instance, if the blood sugar level is below 120, I want to display that point as an orange dot. If it's above 180, I want to show ...

Is it possible to determine whether a path leads to a directory or a file?

Is it possible to distinguish between a file and a directory in a given path? I need to log the directory and file separately, and then convert them into a JSON object. const testFolder = './data/'; fs.readdir(testFolder, (err, files) => { ...

Loading information into deep arrays within MongoDB

What is the most effective way to add data to an array that is deeply nested within multiple levels of arrays... Consider this example document (fictitious) representing the structure of a larger document with several schools, classes, and students: { ...

Issue: Missing Controller

I am facing an issue with two directives where I want to expose an API from one directive for others to use. Even after following the instructions in this example, I keep encountering this error when trying to access the controller of the other directive: ...

Error: The PHP contact form is displaying field names instead of the actual values being entered

I am completely new to this and would appreciate some guidance. I have set up a contact form on a website, but I seem to be encountering some errors. Here is the email content I receive from the contact form: <p>$usersname has contacted you from you ...

Showing ng-attributes in haml partials in Rails using jQuery ajax and $q

As I work on developing an Angular Frontend for an existing Rails Application, I have come across the challenge of integrating $q in my current setup. While I understand that transitioning to a REST API served directly to ngResource would be ideal, the com ...

Using jQuery to find duplicated records within two JSON object arrays

Here is the structure of my first Json Array: [ {"Invent":"4","Beze":"256","mail":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f7f4f5d6f7f4f5b8f5f9fb">[email protected]</a>"}, {"Invent":"4","Beze":"2 ...

`A brief disruption in loading the visual style of Google Maps`

Using the Ionic Framework, AngularJS, and Google Maps API, I encountered an irritating issue with my mobile app. Every time the map loads, there is a noticeable delay in loading the map style. This delay is particularly problematic as my map style converts ...

Obtain the values from this JSON array

o = { "photos": { "page": 1, "pages": 46, "perpage": 5, "total": "230", "photo": [{ "id": "6643924777", "owner": "34653895@N08", "secret": "3b7c2f6469", "server": " ...

The application is resetting when the "$http" method accesses the initial ADAL "protected" URL for the first time

I have created a page inspired by the Angular SPA ADAL sample which can be found here Upon returning from the Microsoft login page and accessing my API secured with AAD, the angular .config() function is called multiple times. This causes issues with upda ...

HTML display issue: Angular curly braces failing to show up

I am facing a peculiar issue in my browser where the content inside the angular curly braces is not being displayed. Even though there are no errors in the console and the value gets logged successfully, the page appears blank. The expected output should b ...