简体   繁体   中英

AngularJS $http.post simple method is not working

I tried to use Angular $http.post(url, data) method. But I am facing some problems to post correct data to server (WebAPI). I have tried follwing options but none is working.

var data1 = new Object();
    data1.UserName = "UserA1";
    data1.Password = "password123";
    data1.ConfirmPassword = "password123";

var data2 = angular.toJson(data1);

var data3 = JSON.stringify(data1);

var data4 = { UserName: "UserA2", Password: "password123", ConfirmPassword: "password123" };

var data5 = "UserName=UserA3&Password=password123&ConfirmPassword=password123";

$http.post(url, data1)
$http.post(url, data2)
$http.post(url, data3)
$http.post(url, data4)
$http.post(url, data5)

None is working. What kind of data is correct for this method. I tried JQuery.post() with above data and it works. Its super strange for me why this simple angularjs method so hard to use or I am missing something.

Update: Basically I am working on following example. I want to register user from client side ( /api/Account/Register ). http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api

This is because your server-side expects a request with its content x-www-form-urlencoded .

jQuery's $.post() sends the request with a Content-type of application/x-www-form-urlencoded whereas Angular's $http.post() sends the request with a Content-type of application/json (and also encodes the data as JSON (instad of form-data) if a JS Object is passed).

There are methods you can send x-www-form-urlencoded requests using $http (and there are several related answers on SO), but it involves less straight-forward code.
I suggest you change your server side to consume JSON requests.

Depending on what you have on server side, you should transform your request (that's the case for PHP, for example, or you can read from the input stream: php://input).

See this gist: https://gist.github.com/JensRantil/5713606 .

If this is not solving your problem, please inspect the requests angular is creating (using the Developer Tools -> Network tab in Chrome for example), and tell us what you see.

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