有人能告诉我为什么下面的语句没有将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对象发送吗?


当前回答

我写了一个小的PHP帮助函数,允许这两种类型的输入参数:

function getArgs () {
    if ($input = file_get_contents('php://input') && $input_params = json_decode($input,true))
        return $input_params + $_POST + $_GET;
    return $_POST + $_GET;
}

用法:

<?php
    include("util.php"); # above code
    $request = getArgs();

    $myVar = "";
    if (isset($request['myVar']))
        $myVar = $request['myVar'];
?>

因此不需要修改JavaScript。

其他回答

我在使用AngularJS和Node.js + Express 4 + Router时也遇到了同样的问题

路由器期望从post的请求中得到数据。如果我遵循Angular Docs中的例子,这个主体总是空的

符号1

$http.post('/someUrl', {msg:'hello word!'})

但如果我把它用在数据中

符号2

$http({
       withCredentials: false,
       method: 'post',
       url: yourUrl,
       headers: {'Content-Type': 'application/x-www-form-urlencoded'},
       data: postData
 });

编辑1:

否则node.js路由器将期望req中的数据。正文(如使用符号1):

req.body.msg

它还将信息作为JSON有效负载发送。在json和x-www-form-urlencoded中有数组的某些情况下,这是更好的。

它工作。希望能有所帮助。

与JQuery不同,出于学究的考虑,Angular使用JSON格式进行POST 数据从客户端传输到服务器端(JQuery应用x-www-form-urlencoded,尽管JQuery和Angular使用JSON进行数据输入)。因此有两个部分的问题:在js客户端部分和在你的服务器部分。所以你需要:

把js的Angular客户端部分像这样放: http({美元 方法:“文章”, url:“请求url”, data: {'message': 'Hello world'} });

AND

写入服务器部分以接收来自客户端的数据(如果是php)。 $data = file_get_contents("php://input"); $ datasondecode = json_decode($data); $message = $dataJsonDecode->消息; echo $消息;/ /“Hello world”

注意:$_POST将不起作用!

希望这个方法对我有用,对你也有用。

类似OP建议的工作格式和Denison的回答,除了使用$http。而不是$http,仍然依赖于jQuery。

在这里使用jQuery的好处是可以正确地传递复杂对象;反对手动转换为URL参数,可能会混淆数据。

$http.post( 'request-url', jQuery.param( { 'message': message } ), {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

在我的例子中,我是这样解决问题的:

var deferred = $q.defer();

$http({
    method: 'POST',
    url: 'myUri', 
    data: $.param({ param1: 'blablabla', param2: JSON.stringify(objJSON) }),
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(
    function(res) {
        console.log('succes !', res.data);
        deferred.resolve(res.data);
    },
    function(err) {
        console.log('error...', err);
        deferred.resolve(err);
    }
);
return deferred.promise;

您需要使用JSON。为每个包含JSON对象的参数进行stringify,然后使用"$. stringify "构建数据对象。param”:-)

注意:我的“objJSON”是一个JSON对象,包含数组,整数,字符串和html内容。他的总大小是>3500个字符。

没有找到如何使用$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方法在这里。