简体   繁体   English

Angular $ http.post:无法将带有数据的对象发送到服务器。 数据作为字符串起作用,作为对象起作用,而不是

[英]Angular $http.post: cannot send objects with data to server. Data as a string works, as an object - not

I want to send data to server using this function: 我想使用此功能将数据发送到服务器:

var _register = function (email, password, passconfirmation) {
    var data = {
        "Email": email,
        "Password": password,
        "ConfirmPassword": passconfirmation
    };

    return $http.post('/api/Account/Register', data, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });
}

It doesn't work. 没用 My ASP.net web api doesn't receive any data. 我的ASP.net Web API没有收到任何数据。 Every variable on server-side is "null". 服务器端的每个变量均为“ null”。 But when I do this this way: 但是当我这样做时:

var _register = function (email, password, passconfirmation) {
    var data = "email=" + email + "&password=" + password + "&ConfirmPassword=" + passconfirmation;

    return $http.post('/api/Account/Register', data, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });
}

Everything works great. 一切正常。 The problem is: the first way is much clearer than the second one, so I want to use the first one. 问题是:第一种方法比第二种方法清晰得多,因此我想使用第一种方法。 But I have no idea what's wrong :/ 但是我不知道怎么了:/

I've had this issue in the past. 我过去曾遇到过这个问题。 Try 尝试

JSON.stringify(data)

Before passing it to the post. 在将其传递到职位之前。 The object binder on the other side should be able to accept it then. 然后,另一侧的对象资料夹应该能够接受它。

remove the headers in post or change the headers like the following 删除帖子中的标题或更改标题,如下所示

 headers: { 'Content-Type': 'application/json' }

your code should be 您的代码应该是

var _register = function (email, password, passconfirmation) {
    var data = {
        "Email": email,
        "Password": password,
        "ConfirmPassword": passconfirmation
    };

    return $http.post('/api/Account/Register', data, {
        headers: { 'Content-Type': 'application/json' }
    });
}

you need to do like this .. 你需要这样做

since AngularJS, transmits data using 自AngularJS以来,使用

Content-Type: application/json

 return $http.post('/api/Account/Register', {'dataObj' : data  }, {
        headers: { 'Content-Type': 'application/json' }
    });

Your data should be a key/val pair, try: data variable will get to the server under the parameter dataObj 您的数据应为键/值对,请尝试:数据变量将在参数dataObj下到达服务器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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