Nobody Nobody - 3 months ago 7
AngularJS Question

Send post request to express without changing the url

I'm trying to do a login form. I'm using angularjs' ng-submit. When the submit button is clicked, I want the post method to be called in the server without changing the url.

The

post
of express requires a url to which it responds. If my login screen's url is
http://localhost:2000/login
and when submit is clicked, I want the
post
to be called for the same url
http://localhost:2000/login
.

And I don't understand how to use the
url
key of the
$http
.

The login html:

<form ng-controller="loginController" ng-submit="loginFunc()">
<input type="text" name="" ng-model="login">
<input type="password" ng-model="password" name="">
<input type="submit" value="login" name="">




The controller:

.controller('loginController', function($scope, $http) {
$scope.login = ""
$scope.password = "";
$scope.loginArray = [];
$scope.loginFunc() {
$scope.loginArray.push($scope.login);
$scope.loginArray.push($scope.password);
$http({
method: 'POST',
url: 'loginClick',
data: $scope.loginArray
})
}
})


The server.js:

app.get('/login', function(request, response) { //the file sent when /login is requested
response.sendFile(__dirname + "/staticFolder/view/login.html");
})

app.post('/loginCheck', function(request, response) { //call this when submit button is clicked without change in url
console.log(JSON.stringify(request.body) + "req");
})

Answer

Try sending login details as an object instead of sending as in array.It will make your life easy.

.controller('loginController', function($scope, $http) {
    $scope.loginFunc() {
        $http({
                method: 'POST',
                url: '/loginCheck', //not loginClick make sure you have a route to handle this.
                data: {
                    login: $scope.login,
                    password: $scope.password
                }
            })
            .then(function(response) {
                //Success handling
            }, function(err) {
                //Error handling
            });
    }
})

You must respond in each and Every route

Edit 1 use backend as: to use same url /login but with different http verbs(get and post)

app.get('/login', function(request, response) { //the file sent when /login is requested
    response.sendFile(__dirname + "/staticFolder/view/login.html");
});
app.post('/login', function(request, response) { //call this when submit button is clicked without change in url
  console.log(JSON.stringify(request.body) + "req");
  /*
    below will be the logic for handling your interest.
  */
  someIOCall(function Handler(err,resultJson){
    if(err)
      return res.status(500).end();
    res.status(200).end(resultJson)
  })    
})

It should work in scenario.