简体   繁体   中英

Converting to string NodeJS Express http response returns in AngularJS

I am trying to build an angularjs program which talks to express / nodejs api and mysql database.

In login page , I am able to call the api correctly and it connects with mysql and based on right combination of user name and password , I am sending back "password matches" or "failure" .

When I am accessing that on HTML using $scope , I am getting ["password matches"] and not password matches . I have tried toString , splice , etc but no proper result.

Controller

var passStats=[];  
passStats = LoginFactory.validateUserLoginFactory(uName, pWD)      
$scope.pwdStatus = passStats;

Factory

app.factory("LoginFactory", function ($http) {
    var factory = {};

    factory.validateUserLoginFactory = function (UserName, PWD) {

        $http({ method: "POST", url: 'http://localhost:3000/validateUserLogin/', data: { limit: userForm }, cache: false }).then(function (response) {        
           StatusPWD.push(response.data);         

        }, function (error) { console.log(error); });
        return StatusPWD;
    }

    return factory;
});

node.js

res.send('password matches');

HTML

<label>User Name</label>
<input type="text" ng-model="enteredUserName" class="w3-input w3-border w3-padding">
<br>
<label>Password</label>
<input type="text" ng-model="enteredPWD" class="w3-input w3-border w3-padding">
<br>
<input type="button" ng-Click="validateLogin(enteredUserName,enteredPWD)" value="Login" class="w3-btn w3-padding w3-green">
<br> <br> <br>
<label>password {{ pwdStatus}}</label>

It is because you are using StatusPWD.push which is pushing it into an array.

the passStats variable is an array, where you are pushing the response.

you can simply do this to get the value if passStats is an array $scope.pwdStatus = passStats[0] or you can do $scope.pwdStatus = passStats.join("")

I have solved my problem for which I posted the question. I had coded the factory and controller part wrongly. Following modification is giving me proper out put in HTML

Factory

factory.validateUserLoginFactory = function (UserName, PWD) {
    var userForm = {};       
    userForm = { user: UserName, password: PWD };       
    return $http({ method: "POST", url: 'http://localhost:3000/validateUserLogin/', data: { limit: userForm }, cache: false });       
}

Controller

$scope.pwdStatus;
   LoginFactory.validateUserLoginFactory(uName, pWD)  
  .then(function (data) {
        console.log(data.data);
       $scope.pwdStatus = data.data;
    }, function (data) {
        console.log(data);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM