Troubleshooting issues with parsing JSON responses in AngularJS

Being new to using AngularJS, I am encountering an issue with parsing a JSON response. I have user login credentials such as Username and password, and I am attempting to parse them when the user clicks on the login button(). If the username and password match what is stored on the server, I should receive a success message. Below is the HTML code I am currently utilizing:

<form ng-submit="loginform()" name="logform"><br/><br>
<tr ng-repeat="logcred in signinfo"></tr>

<div>
 <label form="emailinput"><b>Email</b></label>
 <input type="email" class="form-control" name="uname" id="emailinput" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3940564c795c41585449555c175a5654">[email protected]</a>" ng-model="logcred.username" >
</div>

<div>
  <label form="pwdinput"><b>Password</b></label>
  <input type="password" class="form-control" name="pwd" id="pwdinput" placeholder="*******" ng-model="logcred.password">
</div>

<a ng-click="reloadPage()" class="navbar-brand" ></a>

<div>
 <button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
 <button class="btn btn-primary" ng-click="submit()" >Login</button>
</div>
</form>

Here is the JavaScript code for handling this process using AngularJS:

app.controller('credientials', function($scope,$http) {
$scope.loginform = function (username, password){
$http.get('http://localhost:3000/loginfo')
.then(
    function successCallback(data){
    $scope.response = data;
if($scope.username === 'response.username' && $scope.password === 'response.password'){
    $scope.signinfo = data.loginfo;
}
else{
    console.log("Error");
    }
})
});

The HTML page displays the variable $scope.response containing the JSON returned by the server, but proper authentication seems to be lacking.

I seem to be missing something crucial here - can anyone provide assistance or advice?

Answer №1

UPDATE

Please review the revised code snippet for authentication on the client side.

if(userData.username == response.data.username && userData.password === response.data.password){
      $scope.signinfo = response.data 
}

The userData variable is obtained from the form submit button. Take a look at how I pass the username and password to the controller using ng-submit="loginform(logcred)".

var myApp = angular.module('myApp', []);

myApp.controller('credentials', function($scope, $http) {
  $scope.loginform = function(userData) {
    console.log(userData);
    $http.post('https://reqres.in/api/users', userData) // provide username and password to mock api in the post
      .then(function(response) {
        if(userData.username == response.data.username && userData.password === response.data.password){
            $scope.signinfo = response.data 
        }
      });
  }
});

// In the above HTTP call, use your URL `http://localhost:3000/loginfo` and in your server-side retrieve the username from the request and check the password for that username in your database. If the password matches what you've entered, then send a success message or user details back to the client side.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="credentials">
  <form ng-submit="loginform(logcred)" name="logform">
    <br/>
    <br>
   {{signinfo}}

    <div>
      <label form="emailinput"><b>Email</b></label>
      <input type="email" class="form-control" name="uname" id="emailinput" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="11687e64517469707c617d743f727e7c">[email protected]</a>" ng-model="logcred.username">
    </div>

    <div>
      <label form="pwdinput"><b>Password</b></label>
      <input type="password" class="form-control" name="pwd" id="pwdinput" placeholder="*******" ng-model="logcred.password">
    </div>

    <a ng-click="reloadPage()" class="navbar-brand"></a>

    <div>
      <button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
      <button class="btn btn-primary">Login</button>
    </div>
  </form>
</div>

In the above HTTP call, utilize your URL http://localhost:3000/loginfo. Within your server-side logic, fetch the username from the request and verify the password associated with that username in your database. If the passwords match, deliver a success message or user details to the client side.

Where should I implement the if condition to validate user credentials?

You should apply the if condition within the server-side logic where you retrieve data from the database, such as in your server endpoint (/loginfo).

if(userpassword == passwordfromDB){
  // Send a success message to the client side
} 

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

The Angular Date Pipe is displaying an incorrect date after processing the initial date value

Utilizing Angular's date pipe within my Angular 2 application has been beneficial for formatting dates in a user-friendly manner. I have successfully integrated API dates, edited them, and saved the changes back to the API with ease. However, an issue ...

Adjust the Material UI card to fill the maximum available height

I'm currently working with Material UI Card components. You can find more information here. My goal is to set a maximum height for these cards, ensuring that the text and images are displayed nicely. How should I approach this? Below is a snippet of ...

What is the best way to remove words from an object's value that begin with a specific keyword using JavaScript?

Here is a sample array. I need to remove the words row-? from the className property. [ { type: "text", name: "text-1632646960432-0", satir: "1", className: "form-control col-lg-3 row-1" }, { ...

Show an empty table/data grid with blank rows using Material UI

I am attempting to showcase a table with empty lines and a predefined height, even when there is no data to display initially. By default, the table appears without any visible lines. My goal is to have these empty lines displayed, ensuring that the table ...

Utilizing the reduce method to process an object and return a collection of objects

I have a complex object that I'm trying to transform using the reduce method, but I'm struggling to figure it out... Here is the structure of my object: const object = { ... } My goal is to create a new object with keys that are a combinatio ...

Unable to reset input in a functional component using React JS

I have a component named TextInput that is responsible for rendering an input element: function TextInput({ type = "text", label, name, required = false }) { const [value, setValue] = useState(""); function handleChange(e) { se ...

Tips for maintaining the dropdown selection when new rows or columns are added to a table

I have a task requirement where I must generate a dynamic table using jQuery. I've successfully implemented adding dynamic columns or rows to the table. Feel free to check out the fiddle code here. HTML: <div id='input_div' name='i ...

Retrieve the JSON data from a different local server

I'm currently working on two different websites, with the first being located at https://localhost:44300/ and the second at https://localhost:44301/. Within the Home controller of the second localhost, I have defined the following: [HttpPost] public ...

What advantages does declaring a backing model "class" that closely resembles the GraphQL "Type" bring when using GraphQL?

I appreciate the Universal Relay Boilerplate for its meticulous organization and thoughtful structure compared to other boilerplates. It seems like they really put a lot of effort into ensuring everything is well-planned from the start, which is not always ...

Tips on transmitting a PDF document through JSON using my RESTful service to distribute to clients

Can JSON be used to transmit binary data? I am developing a REST Service using ASP.NET MVC and need to send a PDF file from my server to clients. How can I achieve this when using JSON and XML for data transfer? ...

The download attribute in HTML5 seems to be malfunctioning when encountering a 301 Moved Permanently

I am attempting to create an automatic download feature for a file from a URL with a 301 Moved Permanently redirection. Here is the current code: <a href="myserverapi/download?fileId=123" download="image.jpg" target="_blank" ...

The Angular @Input directive may be prone to receiving inaccurate model data

I am currently working on setting up @Input for my component using a model that resembles the following: interface Car { sail?: never tires: number weight: number } interface Boat { tires?: never sail: boolean weight: number } exp ...

Is it possible to access prop properties within the ready() function?

I am seeing the error message undefined in the console, specifically originating from the ready() function. The issue I am encountering is related to attempting to assign the value of this.users.name to this.userForm.name. Can someone please point out wh ...

Having a problem with the glitch effect in Javascript - the text is oversized. Any tips on how to resize

I found some interesting code on the internet that creates a glitch text effect. However, when I implement it, the text appears too large for my webpage. I'm struggling to adjust the size. Here is the current display of the text: too big This is how ...

Fixing Firefox Bug: How to Eliminate Non-Numeric Characters from "Number" Input Fields

Completing this task seems straightforward. I need to eliminate any non-numeric characters from an input field specified as type "number" in Firefox when a key is pressed. The code snippet provided: $("#field").on("keyup", function() { regex = /[\& ...

Custom JavaScript function throwing an error

function changeElementClass(path, changeClass, duration){ $(path).removeClass(changeClass); $(this).addClass(changeClass); )}; $('.flightDetails .option').changeElementClass('.flightDetails .option','selected',300); ...

When applying a cell formatter to change the color of a Tabulator cell, the text displayed is being

I am attempting to dynamically change the color of a tabulator cell based on its input. My initial approach was to simply try changing the cell's color. After running the following code, here is what I observed: function testFormatter(cell, formatt ...

Creating numerous hash codes from a single data flow using Crypto in Node.js

Currently, I am developing a Node.js application where the readable stream from a child process' output is being piped into a writable stream from a Crypto module to generate four hash values (md5, sha1, sha256, and sha512). However, the challenge ari ...

What is the best way to eliminate duplicate values from an Array in ReactJS?

Hi there, I'm new to JavaScript and React. I need some help with a project I found on the React blog. I want to try solving it in my own way. This is the content of todoList.js: const todoList = [ {category: 'Sporting Goods', price: &a ...

Utilizing an undefined constant in angular programming may lead to unexpected errors

Seeking assistance in generating random first and last names based on gender for a form using Angular. I am relatively new to Angular and keep encountering this error whenever the Use of undefined constant firstName - assumed 'firstName' Here ...