0

I am trying to send a POST request with form data.

Using .save(data) on $resource('http://localhost:5000/api/auth');-object sends the following corresponding cURL string (extracted with Chrome): curl 'http://localhost:5000/api/auth' -H 'Pragma: no-cache' -H 'Origin: http://localhost:63342' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: da-DK,da;q=0.8,en-US;q=0.6,en;q=0.4' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36' -H 'Content-Type: application/json;charset=UTF-8' -H 'Accept: application/json, text/plain, */*' -H 'Cache-Control: no-cache' -H 'Referer: http://localhost:63342/public_html/app/index.html' -H 'Connection: keep-alive' -H 'X-FirePHP-Version: 0.0.6' --data-binary '{"username":"admin","password":"mypass"}' --compressed

And my API does not get any form data. However, when I use curl -X POST --data "username=engel&password=mypass" http://localhost:5000/api/auth my API returns 200 SUCCESS.

How can I use $resource to post a similar request as the working one?

The API allows replies that Access-Control-Allow-Origin http://localhost:63342 is allowed.

EDIT I use the following factory:

factory('AuthResource', ['$resource', function($resource) {
    return $resource('http://localhost:5000/api/auth');
}]);

and then I call it with

var login = AuthResource.save(user);

where user is a dict with username and password

YnkDK
  • 681
  • 9
  • 26

1 Answers1

1

You are sending a standard POST request with the $resource service. This means it will send your username and password as JSON object in the body of the request.

The CURL request you do sends data as url-encoded form data. This is also what your API expects.

If you want to do the same in angular, you must tell your $resource to also send it as form-data.

Just update your factory by adding a new method to the $resource service:

factory('AuthResource', ['$resource', function($resource) {
    return $resource(
        'http://localhost:5000/api/auth', 
        {},
        {
           login: { 
              method: 'POST',
              headers: {
                  'Content-type': 'application/x-www-form-urlencoded'
              }
              tranformRequest: function (data, headersGetter) {
                  var str = [];
                  for (var d in data) {
                      str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
                  }
                  return str.join("&");
              }
           }
        }
    );
}]);

This custom method sends the correct headers but also transforms your JSON object with credentials into an url-encoded string.

You can then use this new method to authenticate with your api:

var login = AuthResource.login(user);
FlorianTopf
  • 938
  • 6
  • 10