简体   繁体   English

如何将数据从bone.js的客户端传递到服务器。 Express + Backbone.js

[英]How to pass the data from backbone.js's client to server. Express + Backbone.js

I'm trying to pass the data from client to server via Backbone.js's save() method. 我正在尝试通过Backbone.js的save()方法将数据从客户端传递到服务器。

todo.js todo.js

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.js(Express) app.js(Express)

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.

});

app_view.js(Backbone.js) is like this... app_view.js(Backbone.js)就像这样...

... 


 // 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);
                    }
        });

This code doesn't send data pass from client to server. 此代码不会将数据传递从客户端发送到服务器。 Do you have any idea? 你有什么主意吗? Thanks in advance. 提前致谢。

Your model data won't be directly on the request object in Express (req.title). 您的模型数据不会直接在Express(要求标题)中的请求对象上。

Assuming you've configured express to use the bodyParser() to parse HTTP POST Bodies 假设您已配置express以使用bodyParser()解析HTTP POST 主体

app.use(express.bodyParser());

Then your Backbone model will be in request.data: 然后,您的Backbone模型将位于request.data中:

app.post("/api/todos",function(req,res){
        console.log(req.body.title);

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM