$ http.post不能以字符串形式发送数据,但json有效

时间:2018-03-29 09:08:16

标签: angularjs http

我正在拨打angularjsnodejs的电话。当我做$http.post时,我能够发送数据,如果它的json但不是字符串,我无法理解我哪里出错了!这是相关的angularjs代码: $scope.categoriesSend是一个字符串

此代码就像一个魅力:

$scope.checkCicks = function() {
    var dict = $scope.selectedCategories;
    console.log($scope.selectedCategories);
    $scope.categoriesSend = "";
    for (var eachkey in dict) {
        console.log(eachkey, dict[eachkey]);
        if (dict[eachkey] === true) {
            var fields = eachkey.split('--');
            console.log(fields[0])
            if ($scope.categoriesSend != "") {
                $scope.categoriesSend = $scope.categoriesSend.concat("\n");
            }
            $scope.categoriesSend = $scope.categoriesSend.concat(fields[0]);
        }
    }
    console.log("Check");
    console.log($scope.categoriesSend);
    console.log("Check");
    // $scope.dataToSend = {data : "yes"}
    $scope.dataToSend = {
        data: $scope.categoriesSend
    }
    $http.post('/writeCategories', $scope.dataToSend).then(function(response) {
        console.log("Done");
    });
}

但是,如果我尝试按原样发​​送字符串 - 它会显示the server responded with a status of 400 (Bad Request)

$http.post('/writeCategories', $scope.categoriesSend).then(function(response) {
    console.log("Done");
});

这是nodejs后端代码

writeCategories: function(req, res, next) {
        console.log("Here");
        console.log(req.body.data);

        var data = req.body.data;
        var newPath = path.join("public", "process", "categories.txt");
        fs.writeFile(newPath, data, function(err) {
            if (err) throw err;
        });
        res.json({status: "done"});
    },

0 个答案:

没有答案