AngularJS HTTP POST不发送数据
我必须通过HTTP POST使用Angular JS发送简单的JSON对象。AngularJS HTTP POST不发送数据
我有一个简单的NG-CLIK连接功能:
$scope.requestGoogleAuth = function() {
var googleCredentials = {
email: '[email protected]',
password: 'a2s4d'
};
console.log(JSON.stringify(googleCredentials));
/*$http({
url: '/MyServlet',
method: "POST",
data: JSON.stringify(googleCredentials),
headers: {'Content-Type': 'application/json'}
})*/
$http.post("/MyServlet", JSON.stringify(googleCredentials)).then(function success(response) {
$('#loginGoogleModal').modal('hide');
$("#notificationsWrapper").notify(
"Logged with Google",
{
className: 'success',
position: 'bottom right'
}
);
$scope.googleLogged = true;
console.log($scope.googleLogged);
}, function error(response) {
$('#loginGoogleModal').modal('hide');
$("#notificationsWrapper").notify(
"Failed to login with Google",
{
className: 'error',
position: 'bottom right'
}
);
$scope.googleLogged = false;
console.log($scope.googleLogged);
});
};
我控制器配置为:
iftttApp.controller('indexController',
['$scope', '$routeParams', '$window', '$http', function ($scope, $routeParams, $window, $http,) { ... });
的POST成功地达到我的servlet成功返回,但是JSON不要放在HTTP消息,POST数据结果为空。为什么?
请尝试以下代码。实际上你的帖子不是一个正确的密钥对,在你的帖子请求中的值为json。
$scope.requestGoogleAuth = function() {
var googleCredentials = {
email: '[email protected]',
password: 'a2s4d'
};
console.log(JSON.stringify(googleCredentials));
/*$http({
url: '/MyServlet',
method: "POST",
data: JSON.stringify(googleCredentials),
headers: {'Content-Type': 'application/json'}
})*/
var postvalue = {
"nome": $scope.nome,
"regione": $scope.regione
}
$http.post("/MyServlet", angular.toJson(postvalue)).then(function success(response) {
$('#loginGoogleModal').modal('hide');
$("#notificationsWrapper").notify(
"Logged with Google",
{
className: 'success',
position: 'bottom right'
}
);
$scope.googleLogged = true;
console.log($scope.googleLogged);
}, function error(response) {
$('#loginGoogleModal').modal('hide');
$("#notificationsWrapper").notify(
"Failed to login with Google",
{
className: 'error',
position: 'bottom right'
}
);
$scope.googleLogged = false;
console.log($scope.googleLogged);
});
};
看来你发布的是字符串,而不是json对象 –
那就是为什么我使用angular.toJson()将其转换为JSON。这个对我有用。 –
我更正了代码,测试了“angular.toJson(googleCredentials)”,但无法正常工作。 – kitsune
我的控制器的配置是: 'iftttApp.controller( 'indexController的',[ '$范围', '$ routeParams', '$窗口', '$ HTTP', 函数($范围,$ routeParams,$ window,$ http,){...});' – kitsune
“JSON不放在HTTP消息中,POST数据结果为空” - 你如何确定这个?您是否使用浏览器中的开发人员工具来检查网络流量?你是否试图用一些你没有在问题中包含的服务器端Java来阅读它? – Quentin
$ scope.nome和$ scope.regione是否定义? –