有人能告诉我为什么下面的语句没有将post数据发送到指定的url吗?url被调用,但在服务器上,当我打印$_POST -我得到一个空数组。如果我在控制台中打印消息,然后将其添加到数据-它显示了正确的内容。

$http.post('request-url',  { 'message' : message });

我也尝试过将数据作为字符串(具有相同的结果):

$http.post('request-url',  "message=" + message);

当我以以下格式使用它时,它似乎正在工作:

$http({
    method: 'POST',
    url: 'request-url',
    data: "message=" + message,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});

但是是否有一种方法可以用$http.post() -我总是必须包括头以便它工作吗?我相信上面的内容类型是指定发送数据的格式,但我可以把它作为javascript对象发送吗?


当前回答

用这种方法。没必要写这么多

 isAuth = $http.post("Yr URL", {username: username, password: password});

在nodejs的后端

app.post("Yr URL",function(req,resp)
{

  var username = req.body.username||req.param('username');
  var password = req.body.password||req.param('password');
}

我希望这对你们有帮助

其他回答

你可以这样设置默认的“Content-Type”:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

关于数据格式:

美元的http。Post和$http。put方法接受任何JavaScript对象(或字符串)值作为其数据参数。如果data是一个JavaScript对象,默认情况下,它将被转换为JSON字符串。

试着使用这种变化

function sendData($scope) {
    $http({
        url: 'request-url',
        method: "POST",
        data: { 'message' : message }
    })
    .then(function(response) {
            // success
    }, 
    function(response) { // optional
            // failed
    });
}

我喜欢使用函数将对象转换为post参数。

myobject = {'one':'1','two':'2','three':'3'}

Object.toparams = function ObjecttoParams(obj) {
    var p = [];
    for (var key in obj) {
        p.push(key + '=' + encodeURIComponent(obj[key]));
    }
    return p.join('&');
};

$http({
    method: 'POST',
    url: url,
    data: Object.toparams(myobject),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

It's not angular's fault. Angular is designed to work in JSON world. So when $http service send AJAX request, it send all your data as a payload, not as form-data so that your backend application can handle it. But jQuery does some things internally. You instruct jQuery's $ajax module to bind form-data as JSON but before sending AJAX request, it serialized JSON and add application/x-www-form-urlencoded header. This way your backend application able to received form-data in form of post parameters and not JSON.

但是你可以修改angular $http服务的默认行为

添加标题 序列化json

$httpParamSerializerJQLike是angular的内置服务,它以同样的方式序列化json。jQuery的参数。

$http({
    method: 'POST',
    url: 'request-url',
    data: $httpParamSerializerJQLike(json-form-data),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
    }
});

如果你需要一个插件先将表单数据序列化成JSON,可以使用这个插件https://github.com/marioizquierdo/jquery.serializeJSON

要通过Post方法和angularjs的$http发送数据,你需要改变

数据:"message=" +消息,数据:$.param({消息:消息})

没有找到如何使用$http的完整代码片段。Post方法将数据发送到服务器,以及为什么在这种情况下它不工作。

以下代码段的解释…

我使用jQuery $。param函数将JSON数据序列化为www post data 在配置变量中设置Content-Type,该变量将随angularJS $http请求一起传递。通知服务器我们将以WWW Post格式发送数据。 注意$ http。post方法,我发送的第一个参数作为url,第二个参数作为数据(序列化)和第三个参数作为配置。

剩下的代码是自己理解的。

$scope.SendData = function () {
           // use $.param jQuery function to serialize data from JSON 
            var data = $.param({
                fName: $scope.firstName,
                lName: $scope.lastName
            });

            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }

            $http.post('/ServerRequest/PostDataResponse', data, config)
            .success(function (data, status, headers, config) {
                $scope.PostDataResponse = data;
            })
            .error(function (data, status, header, config) {
                $scope.ResponseDetails = "Data: " + data +
                    "<hr />status: " + status +
                    "<hr />headers: " + header +
                    "<hr />config: " + config;
            });
        };

查看$http的代码示例。Post方法在这里。