Meteor如何将数据从客户端传递到服务器端

4
我有一个注册表格,当用户点击提交按钮时,每个文本框中的值将被发送到服务器以插入该数据,并返回真/假。
客户端:
Template.cust_register.events({
    'click button': function(){
          var email = $('#tbxCustEmail').val();
          var msg = $('#tbxCustMsg').val();
          var isSuccess = insertMsg(email,msg);
          if(isSuccess){
             alert("Success");
          }else alert("Try again");
    }
});

服务器:
function insertMsg(email,msg){
     Messages.insert({Email:email,Message:msg});
     return true;
}

这个方法最终没有奏效。 如何解决这个问题? 许多人建议使用“发布/订阅”的方法,但我不知道怎么使用。

1
你应该认真学习发布/订阅模型;这几乎是Meteor的基本理念,如果你不理解它的含义,使用Meteor会非常困难。 - JJJ
2个回答

4

首先观看入门视频并阅读文档中的数据和安全性部分。

在发布/订阅模式下,您的代码应该如下所示:

通用:

Messages = new Meteor.Collection('messages');

客户:

Meteor.subscribe("messages");

Template.cust_register.events({
    'click button': function(){
          var email = $('#tbxCustEmail').val();
          var msg = $('#tbxCustMsg').val();
          Messages.insert({Email:email,Message:msg});
    }
});

服务器:

Meteor.publish("messages", function() {
    return Messages.find();
});

在Meteor中,我们可以在客户端进行插入操作吗?哇,那太危险了 :( - yozawiratama
1
阅读本章。在进行初始原型设计后,您需要meteor remove insecure并定义对集合的访问规则。 - rzymek
2
@yozawiratama,使用允许规则在将它们插入服务器之前检查它们并不危险,这就像拥有权限一样。 - Tarang
1
@yozawiratama 你必须使用Meteor编写一些不同的项目来理解它。这并不危险,而且非常安全。 - delibalta

4

另一种解决方案是在客户端使用Meteor.call('yourMethodName')

然后,在服务器上,你可以有

Meteor.methods({
    yourMethodName: function() { /* validate input + return some data */ }
});

您可以考虑将返回值设置为会话变量。
Meteor.call('yourMethodName', function (err, data) {
    if (!err) {
        Session.set('myData', data);
    } 
});

然后在某些模板中...

Template.whatever.helpers({
    messages: function() {
        return Session.get('myData');
    }
});

为什么要做这些呢?
1) You can explicitly deny all direct `insert/update/find` queries from the client, and force usage of pre-defined Meteor methods.

2) You can manually determine when certain data is "refreshed".

显然,这种方法破坏了订阅/出版模型的价值,只有在不需要实时数据的情况下才应该使用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接