我尝试使用AngularJS v 1.5.8从HTML表单调用POST请求(使用Jersey APi for REST)。
我有一个HTML表单,其中包含一个调用REST服务的提交按钮:
<body ng-app="myApp" ng-controller="loginController">
......
<form name="myForm" nonvalidate ng-submit="login()">
......
<div
class="col-md-4 col-md-offset-4 col-sm-4 col-sm-offset-3 col-xs-6 col-xs-offset-3">
<button type="submit" class="btn btn-default" ng-submit="login()">Submit</button>
</div>
</form>
这是我的loginController脚本:
var app = angular.module ("myApp", []);
app.controller("loginController", function($scope, $http){
$scope.username = "";
$scope.password = "";
$scope.login = function() {
var transform = function(data) {
return $.param(data);
}
$http(
{
url : 'http://localhost:8080/RestServices/services/user/add',
method : 'POST',
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
},
transformRequest : function(data) {
return $.param(data);
},
data: { name: $scope.username,
password: $scope.password }
}).success(function(response, status) {
$scope.data = response; //Assign data received to $scope.data
}
)
}
}
)
这是我简单的REST邮政服务:
@Path("user")
public class UserResource {
private TreeMap<Integer, User> userMap = new TreeMap<Integer, User>();
@POST
@Path("add")
@Consumes({MediaType.APPLICATION_JSON})
public Response addUser(User user) {
int id = userMap.size();
user.setId(id);
userMap.put(id, user);
ObjectMapper mapper = new ObjectMapper();
String jsonString = "";
try {
jsonString = mapper.writeValueAsString(user);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
jsonString = null;
}
return Response.ok().entity(jsonString).build();
}
}
调用POST请求但返回415错误:服务器拒绝了此请求,因为请求实体的格式不受所请求方法所请求资源的支持。
答案 0 :(得分:0)
function loginController($scope, $http) {
$scope.username = "";
$scope.password = "";
$scope.login = function () {
$http({
method: 'POST',
url: 'user/add',
data: {
username: $scope.username,
password: $scope.password
}
}).success(function (data, status, headers, config) {
$scope.result =data.username;
alert($scope.result);
}).error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
}
答案 1 :(得分:0)
问题出在REST API期望的格式,即{
"name": "project",
"version": "1.0.0",
"dependencies": {
"left-pad": "1.0.0",
"c": "file:../c-1",
"d2": "file:../d2-1"
},
"resolutions": {
"d2/left-pad": "1.1.1",
"c/**/left-pad": "1.1.2"
}
}
。
因此,尝试使用JSON
并不需要指定字符集:
application/json