[英]Sending data from AngularJs to NodeJs issue
I'm gonna start by showing you my code 我将从显示我的代码开始
Angular Code: app.js 角度代码:app.js
$scope.submit = function(){
$scope.jsonData={
"status":"OK",
"data":{
"nbOperatorPresent": $scope.nbOperatorPresent,
"objectif1stHour": $scope.objectif1stHour,
"objectif2ndHour": $scope.objectif2ndHour,
"objectif3rdHour": $scope.objectif3rdHour,
"objectif4thHour": $scope.objectif4thHour,
"objectif5thHour": $scope.objectif5thHour,
"objectif6thHour": $scope.objectif6thHour,
"objectif7thHour": $scope.objectif7thHour,
"objectif8thHour": $scope.objectif8thHour
}
}
$http.post("http://localhost:5000/settings",
JSON.stringify($scope.jsonData)).success(function(data,status){
console.log('success')
})
}
NodeJs Code: index.js NodeJs代码:index.js
app.post('/settings',urlencodedParser,function(req,res){
console.log(req.body)
})
As you can see, I have a button to submit the data inserted by the user and send it to the server. 如您所见,我有一个按钮来提交用户插入的数据并将其发送到服务器。
My problem is, when I hit submit, there is nnothing in my browser console, I mean console.log('Success !')
didn't work, that is to say that all the code inner the .success(function(data,status))
won't be executed so I can't notify the user that he has submitted Successfully, I don't know where the problem came from !! 我的问题是,当我点击“提交”时,我的浏览器控制台中出现了很多问题,这意味着
console.log('Success !')
无法正常工作,也就是说, .success(function(data,status))
将不会执行,因此我无法通知用户他已成功提交,我不知道问题出在哪里!
BUT In the other console console.log(req.body)
I found all the data that has been passed from Angular . 但是,在另一个控制台
console.log(req.body)
我找到了已从Angular传递的所有数据。
Can anyone explain this to me ? 谁能向我解释一下? I've tried other solutions but always the same problem :(
我试过其他解决方案,但始终是相同的问题:(
You're not returning anything from the node.js code. 您不会从node.js代码返回任何内容。 You need to add in a returning data like:
您需要添加返回数据,例如:
app.post('/settings',urlencodedParser,function(req,res) {
console.log(req.body)
res.send("Success")
})
To expand on the answer... 为了扩大答案...
Please note if you are unfamiliar with node and express you may want to get in the habit of returning 请注意,如果您不熟悉node并表示您可能想养成返回的习惯
res.send(success: true, data: res).end()
Its very typical on the angular or UI side to be able to parse as response.data object. 它在角度或UI方面非常典型,可以解析为response.data对象。 Just a suggestion.
只是一个建议。
and change to this: 并更改为:
.success(function(res,status){
console.log(res.success, res.data)
})
This is a very common architecture especially when dealing with web services that you have not control over. 这是一个非常常见的体系结构,尤其是在处理您无法控制的Web服务时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.