Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending a POST request with Angularjs and get parameters in a Flask backend

I have this code in AngularJS:

myApp.controller('LoginCtrl', function($scope, $http){
  $scope.formData = {};

  $scope.doLogin = function(url, pass){
    $http({
      url: url,
      method: "POST",
      data: $.param($scope.formData)
    }).success(function(data) {
      console.log(data)
    });
  }
});

And in the beckend (Flask), I have this:

def user_authenticate():
    login = request.args.get('login')
    password = request.args.get('password')
    print login, password

The problem is that request.args come empty.

like image 204
rafaels88 Avatar asked Jan 11 '23 18:01

rafaels88


1 Answers

UPDATE

After have a lot of problems with this, I solve using another Stackoverflow answer. So, I got this code:

ANGULARJS

$scope.doLogin = function(url, pass){
    $http({
      url: url,
      method: "POST",
      headers: { 'Content-Type': 'application/json' },
      data: JSON.stringify(data)
    }).success(function(data) {
      console.log(data)
    });
 }

FLASK

def view_of_test():
    post = request.get_json()
    param = post.get('param_name')

OLD VERSION

I just figured that I need to change my code to this:

AngularJS:

myApp.controller('LoginCtrl', function($scope, $http){
  $scope.formData = {};

  $scope.doLogin = function(url, pass){
    $http({
      url: url,
      method: "POST",
      data: $.param($scope.formData),
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    }).success(function(data) {
      console.log(data)
    });
  }
});

Just include the 'Content-Type' header.

Flask:

def user_authenticate():
    login = request.form.get('login')
    password = request.form.get('password')
    print login, password

Instead of use request.args, use request.form.

like image 119
rafaels88 Avatar answered Jan 30 '23 02:01

rafaels88