Angularjs POST请求有效(状态200),但满足失败条件
以下是我提出请求的AngularJS代码:Angularjs POST请求有效(状态200),但满足失败条件,angularjs,grails,Angularjs,Grails,以下是我提出请求的AngularJS代码: $scope.add = function(){ // Function used to add a value to list. Value has name, type, and priority. if($scope.thing){ $scope.items.push( {name: $scope.thing, type: $scope.worktypeSelecti
$scope.add = function(){ // Function used to add a value to list. Value has name, type, and priority.
if($scope.thing){
$scope.items.push(
{name: $scope.thing,
type: $scope.worktypeSelection,
priority: $scope.prioritySelection,
completed: false,
comments: '',
creator: $scope.username,
assignedTo: $scope.assign
});
var itemToJson = $scope.items[$scope.items.length - 1];
$http.post('http://localhost:8080/server/todoList/addItem', {itemToJson})
.success(function(response) {alert("success");})
.error(function(response) {alert("fail");});
$scope.thing = '';
}
else{
alert("Empty task is not allowed!");
}
};
还有我的Grails控制器:
package server
import grails.converters.JSON
class TodoListController {
def addItem() {
def newItem = new Item(request.JSON)
newItem.save(flush: true)
render newItem as JSON
}
def index(){
render Item.list() as JSON
}
}
及其域类:
package server
class Item {
String name
String type
String priority
boolean completed = false
String comments
String creator
String assignedTo
static constraints = {
name nullable: false
priority nullable: true
type nullable: true
comments nullable: true
creator nullable: false
assignedTo nullable: false
}
}
当我开始发帖时,我从网络上得到一个200,据说这意味着发帖是可以的,但随后我得到了失败的结果,警报弹出失败。如果请求实际上到达了服务器,我不明白问题是什么itemToJson已经是json对象了 不要在{}之间插入 像这样:
$http.post('http://localhost:8080/server/todoList/addItem', itemToJson)
你能试试then方法吗?我已经对error/success方法有了一些问题:
$http.post( 'url', data ).then(
function( result ) {
// success callback
},
function( error ) {
// error callback
}
);
否则,问题可能是服务器返回的json不正确。当服务器返回某个内容时,http状态代码为200。但这并不意味着数据是格式良好的JSON。检查JSON是否正确。问题似乎与CORS和我的浏览器有关。我在IE中试过,效果很好。意识到这一点后,我想在花了好几个小时的时间之后把头发拔出来,我下载了允许CORS的chrome,现在它或多或少可以工作,有一些纠结,但现在有了持久性 谢谢你的提醒,但这并没有解决问题。很高兴知道!如何检查从服务器发送的数据?只需在发送前打印数据,或者在你的chrome开发工具中,你可以在“网络”选项卡中看到有关HTTP请求的信息。我没有得到chrome上可用的请求数据。只有在发送请求时打开面板,开发工具才会捕获请求。你知道该怎么办吗?这是我访问addItem时得到的结果,我假设这是问题所在:保存期间发生验证错误:-字段“名称”上的对象“服务器”中的字段错误:“项”:拒绝值[null];