我正在尝试通过Backbone.js的save()方法将数据从客户端传递到服务器。
window.Todo = Backbone.Model.extend({
initialize:function(){
},
urlRoot:"http://localhost:3000/api/todos",
defaults:{
title:"",
done:false,
important:false,
completed:false
},
toggleDone:function(){
this.destroy();
}
});
app.post("/api/todos",function(req,res){
console.log(req.title); // I want to receive todo item's title which is created new item's.But req.title is undefined.
});
...
// create method make new todoItem and send new todoItem to server.But currently it doesn't work.
create:function(e){
var input = $(this.el).find("#new-todo");
if (e.keyCode !== 13) return;
var text = input.val();
var todo = new Todo({title:text});
// It send POST request to "/api/todos"
todo.save({title: text,body: "hello world"});
var todoView = new TodoView({model: todo});
$("#todo-item").append(todoView.render().$el);
$(input).val("");
this.collection.add(todo);
}
});
此代码不会将数据从客户端传递到服务器。 你有什么主意吗?提前谢谢。
答案 0 :(得分:1)
您的模型数据不会直接在Express(req.title)中的请求对象上。
假设您已配置express以使用bodyParser()来解析HTTP POST Bodies
app.use(express.bodyParser());
然后你的Backbone模型将在request.data:
app.post("/api/todos",function(req,res){
console.log(req.body.title);
});