我正在尝试将JSON数据从前端表单(angularJS)发送到服务器(express / nodejs),然后发送到MongoDB。但是,我似乎无法发送数据,当我在服务器端记录数据时,它给了我一个空的数据字段(请参见下图)。
客户端前端HTTP POST代码
g++ -g -fsanitize=address CMakeFiles/pisa.dir/src/Alphabet.cpp.o {more .o files} -o pisa -L/global/homes/e/esaliya/sali/git/bitbucket/combinatorial-blas-2.0/CombBLAS/_install/lib -Wl,-rpath,/global/homes/e/esaliya/sali/git/bitbucket/combinatorial-blas-2.0/CombBLAS/_install/lib -lCombBLAS -lGraphGenlib -lUsortlib
服务器端(POST请求处理程序)
$http(
{
method: 'POST',
url: 'http://localhost:3456/todo',//Server URL
headers: {
'Content-Type': 'application/json',
'Accept':'application/json'
},
data: {item:'From Angular'}
}).then(function successCallback(response) {
console.log('Congrats, sent to Server');
console.log(response);
}, function errorCallback(response) {
console.log('Not sent to Server');
console.log(response);
});
客户端POST请求(来自angularjs)
应该如何
问题是我似乎无法将“数据”发送到服务器。在服务器端,它显示为空,如图1所示。所有数据最终都位于config-> data(如1中)内,而data字段为空。
答案 0 :(得分:0)
请在下面找到我使用的工作代码,希望对您有所帮助:
JSON(idList.json):
[
{
"id": "G01032014",
"password": "1234"
},
{
"id": "G01032015",
"password": "12345"
},
{
"id": "G01032016",
"password": "123456"
}
]
server.js:
app.post('/authenticate', function(req, res) {
console.log(req.url);
var id = (req.body.id);
var pass = (req.body.pass);
console.log(id);
console.log(pass);
var sendData = {
"status":false,
"user":id
};
var readId = require('./idList.json');
for(var i=0;i<readId.length;i++) {
if(id == readId[i].id && pass == readId[i].password) {
console.log('matched');
sendData.status = true;
i=readId.length;
}
}
res.end(JSON.stringify(sendData));
});
AngularJs控制器:
$scope.auth = function() {
if($scope.id == "" || $scope.pass == null){
alert('please fill details');
} else {
var subData = {
"id":$scope.id,
"pass":$scope.pass
};
$http.post('/authenticate', subData).success(function(data) {
$scope.reponse = data;
console.log($scope.reponse.status);
if ($scope.reponse.status) {
$scope.activate = false;
} else {
alert('incorrect id or password');
}
});
}
$scope.id = '';
$scope.pass = '';
};
HTML:
<div>
<span>Login</span><hr>
User id :<input type="text" ng-model="id" value="id" placeholder="user id" />
Password: <input type="password" ng-model="pass" value="pass"
placeholder="password" />
<input type="submit" value="Login" ng-click="auth()" />
</div>