"Encountering issues with logging in through AngularJS and the $http request functionality

My goal is to login using $http and GET of REST web services. This is my approach:

  1. Retrieve data based on username and password using $http.get
  2. Store the result in $scope.getResult=res;
  3. Assign variables to the retrieved data:

    var result=$scope.getResult; var username=result.userName;
    var password=result.password;
    var user=this.user; var pass=this.pass;

  4. Next, I compare the stored data with the ng-model of username and password. If they match, redirect to another page as shown below:

    if (username == user && password == pass) { window.location="/next.html";
    }

Here's my complete code. Any suggestions on how to improve it would be greatly appreciated.

$scope.login = function () {

  var user = this.user ; // ng-model of username in html page
  var pass = this.pass; //ng-model of password in html page  

  $http.get("http://localhost:17681/api/userRegisters"+user+pass).success(function (res) {

    $scope.getResult = res;

    var result = $scope.getResult;
    var username = result.userName;
    var password = result.password;

    if (username == user && password == pass) {
      window.location="/next.html";
    }

  }

} 

I'm open to any suggestions on how to enhance my code for better functionality.

Thank you in advance :)

Answer №1

Instead of using the raw window.location method, it is recommended to use the AngularJS $location service. Using window.location within a $q service fulfillment handler may lead to an internal error in AngularJS.

$http.get("http://localhost:17681/api/userRegisters"+user+pass)
  .then(function onFulfilled(response) {

    $scope.getResult = response.data;

    var result = $scope.getResult;
    var username = result.userName;
    var password = result.password;

    if (username == user && password == pass) {
      //Use this
      $location.path("/next.html");
      //Not this
      //window.location="/next.html";
    }
}).catch ( function onRejected(response) {
    console.log(response.status);
});

For more information, check out the AngularJS $location Service API Reference.

Deprecation Notice

The $http legacy promise methods .success and .error have been deprecated. It is advised to use the standard .then method instead.1


Debugging the Response

While the response.data provides records, it does not include column records. What steps should be taken to fetch data?

What are the specifications for the server-side API?

Can you provide the server-side code responsible for generating the response data?

Having these details will help others assist you effectively.

It is considered best practice in the industry to avoid transmitting passwords as URL parameters due to security concerns.

The AngularJS team recommends checking out two resources:2

  • Handling User Authentication in an AngularJS Web App

  • Implementing Authentication in Single Page Applications With Angular.js


Additional Resources

Answer №2

" " + user + "&pass=" + pass

retrieve the user and password details from using the GET HTTP request method

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

Attempting to link two JavaScript files, however, only one of them is functioning correctly

I'm currently experiencing an issue with my HTML page that involves calling two JS files for two different image sliders on the same website page. One slider works perfectly fine while the other does not. I'm confused as to whether it's perm ...

Take care of all default document types in the Html5ModeFeature plugin for ServiceStack

This snippet of code represents my first attempt at creating a ServiceStack plugin to support the angularjs configuration $locationProvider.html5Mode(true); when using ServiceStack in a self-hosted environment. This was a requested feature on Stack Overflo ...

What is the best way to input individual students' CA and exam scores into distinct fields and then calculate their total scores in a separate text field?

As a beginner in jQuery, I am looking for guidance on creating a script that calculates the Total score, Grade, Remark, and Position based on the user input of CAT score and EXAM score. The result should be displayed dynamically once both scores are entere ...

Guide to switching classes with jquery

On my webpage, I have a star rating system that I want to toggle between "fa fa-star" and "fa fa-star checked" classes. I found some information on how to do this here: Javascript/Jquery to change class onclick? However, when I tried to implement it, it di ...

Steps for resolving the "endless redirection loop" issue in Sharepoint

I am currently learning Javascript and working on setting up a multi-language Sharepoint site. I am trying to implement a code into each page that checks the user's email and the language in the URL (Portuguese or Spanish) and then redirects according ...

AngularJS Error: The method serviceName.functionName() is not a valid function

I am trying to implement a function that will go back when the cancel button is clicked. Here is the view code: <div ng-controller="goodCtrl"> <button class="btn" ng-click="cancel()">Cancel</button> </div> And here is the Jav ...

Use the row().data function with the datatables.net plug-in to fetch data from a specific column in a

UPDATE: Removed my video on YouTube, but here is a straightforward solution: $(document).on('click', '.edit_btn', function() { var rowData = $('#example').DataTable().row($(this).parents('tr')).data(); }); "Funct ...

What could be causing a parse error and missing authorization token in an AJAX request?

I recently wrote some code to connect a chat bot to Viber using the REST API. The main part of the code looks like this -: $.ajax({ url : url , dataType : "jsonp", type : 'POST', jsonpCallback: 'fn', headers: { 'X-Viber-Auth- ...

Updating a numeric field in Mongoose by a percentage of its current value

Looking for a way to reduce prices of items in Mongoose. { name:"itemname", price: 30 } I want to apply a 10% reduction to the price, but $inc and $mul won't work for this scenario. {$mul: {price:0.10}} This code would reduce the price to 10% of t ...

Is it necessary for the DELETE route to return a 404 error if the resource cannot be found? Looking

Regarding the REST standard for a delete request when the resource is not found, how can this be checked? router.route('/tasks/:id').delete((req, res) => { Task.findByIdAndRemove(req.params.id) .then(() => { // Resp ...

Issue encountered during Azure DevOps pipeline release: D:a 1a***.zip angular - No package matching the specified pattern was discovered

My Angular project stored in an Azure DevOps repository successfully builds using the DevOps build pipeline. However, when it comes to the release, it consistently fails with the following error message: Error: No package found with specified pattern: D:& ...

What is the best way to determine if a JSON response value contains a hyphen '-' in Java Script?

When I receive a JSON response, I sometimes encounter values with hyphens. In JavaScript, the hyphen '-' is treated as a subtraction operator. JSON books": { "red": "2008-17801", "blue": "TERTERIAN-HAYK" } After obtaining these values, I store ...

Tips for integrating custom images or icons into Onsen-UI:

I am currently utilizing the Onsen-UI framework along with AngularJS to create a mobile application. I want to incorporate custom images for buttons, but they appear blurry or unclear on certain mobile devices when the app is launched. Below is my code sn ...

Converting JSON data from an XML document using PHP

While I have a decent understanding of xml and json parsing, I'm facing an issue with this particular site. Here is what I have tried: $json_string="http://meteo.arso.gov.si/uploads/probase/www/plus/timeline/timeline_radar_si_short.xml"; $json = fil ...

Adjust the node_modules path tailored to your project

My current project structure looks like this: |-app |-... |-libs |- package.json |- index.html I am interested in organizing my project such that the 'node_modules' folder is inside the 'libs' folder. The desired structure is as fo ...

CSS tip: Create a trendy design by adding a slanted border to the last

I need help creating a unique menu list with a white border design. The borders should all be straight by default, except for the last border which must be slanted. ul { background-color: #183650; } li { list-style: none; display: inline-block; b ...

Use Puppeteer and Node.js to repeatedly click a button until it is no longer present, then initiate the next step

Imagine a dynamic web page filled with rows of constantly updated data. The number of rows on the page remains fixed, meaning old rows are replaced and not stored anywhere. To navigate through this page, you need to click on a "load more" button that app ...

Substitute the symbol combination (][) with a comma within Node.js

Currently, I am utilizing Node JS along with the replace-in-file library for my project. Within a specific file named functions.js, I have implemented various functions. Furthermore, in another file named index.js, I have added code to call these functio ...

Loop through images in a file directory

Just starting out with Angular and I'm looking to create an ng-repeat of images that are stored in a folder. Each image has its own unique name, so I'm not sure how to approach setting the ngSrc for all of them. Appreciate any help or advice on ...

What might be the reason my $q.defer().resolve is not functioning properly?

I have noticed an interesting behavior in my code. When I define a promise in the service and return it back (promise1 in this case), it does not resolve at all. However, when I define the promise in the controller (promise2), it works perfectly fine. Why ...