我使用grails 3.x作为宁静的服务提供商。提供了一个简单的休息资源,如:
@Resource(uri ='/users', readOnly = false, formats = ['json', 'xml'])
class User {
String username
String email
String password
}
我已成功通过curl测试它,如:
$ curl -H "Content-Type: application/json" -X POST -d "{\"username\":\"xyz\",\"password\":\"xyz\", \"email\":\"w@g.com\"}" http://localhost:8080/users
{"id":1,"email":"w@g.com","password":"xyz","username":"xyz"}
但是当我使用angularjs来执行http post ajax调用时,
$http.post(url, {"username":"dummy", "password":"test", "email":"email@g.com"})
.success(function(data, status, headers, config) {
// $location.path('/listUsers');
console.log("data " + data);
}).error(function(data, status, headers, config) {
console.log("error occured... " + status);
});
即使具有相同的确切值,它也总是抛出422状态。
答案 0 :(得分:1)
您可以将此标题全局放置,如下所示 -
angular.module('myApp', [])
.config(function ($httpProvider) {
$httpProvider.defaults.headers.put['Content-Type'] = 'application/json';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json';
})
答案 1 :(得分:0)
最后我明白了。感谢您的所有意见。
var config = {
'method': 'POST',
'url': "http://localhost:8080/users",
'headers': {
'Content-Type': 'application/json'
},
'data': {"username":"dummy", "password":"test", "email":"email@g.com"}
}
$http(config)
.success(function(data, status, headers, config) {
// $location.path('/listUsers');
console.log("data " + data);
}).error(function(data, status, headers, config) {
console.log("error occured... " + status);
});