Meteor - 方法

Meteor - 方法 首页 / Meteor入门教程 / Meteor - 方法

Meteor方法是在服务器端编写的函数,但可以从客户端调用,在服务器端,无涯教程将创建两个简单的方法。第一个将加5,而第二个将加 10 。

meteorApp.js

	
if(Meteor.isServer) {

   Meteor.methods({

      method1: function (arg) {
         var result=arg + 5;
         return result;
      },

      method2: function (arg) {
         var result=arg + 10;
         return result;
      }
   });
}

if(Meteor.isClient) {
   var aaa='aaa'
   Meteor.call('method1', aaa, function (error, result) {
	
      if (error) {
         console.log(error);
         else {
            console.log('Method 1 result is: ' + result);
         }
      }
   );

   Meteor.call('method2', 5, function (error, result) {

      if (error) {
         console.log(error);
      } else {
         console.log('Method 2 result is: ' + result);
      }
   });
}

启动应用程序后,无涯教程将在控制台中看到计算出的值。

链接:https://www.learnfk.comhttps://www.learnfk.com/meteor/meteor-methods.html

来源:LearnFk无涯教程网

Meteor Methods Log


要处理错误,可以使用 Meteor.Error 方法。以下示例显示了如何为未登录的用户处理错误。

if(Meteor.isServer) {

   Meteor.methods({

      method1: function (param) {

         if (! this.userId) {
            throw new Meteor.Error("logged-out",
               "The user must be logged in to post a comment.");
         }
         return result;
      }
   });
}

if(Meteor.isClient) {  Meteor.call('method1', 1, function (error, result) {

   if (error && error.error === "logged-out") {
      console.log("errorMessage:", "Please log in to post a comment.");
   } else {
      console.log('Method 1 result is: ' + result);
   }});

}

控制台将显示无涯教程的自定义错误消息。

无涯教程网

Meteor Methods Error

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

程序员的数学基础课 -〔黄申〕

玩转Git三剑客 -〔苏玲〕

性能测试实战30讲 -〔高楼〕

正则表达式入门课 -〔涂伟忠〕

容器实战高手课 -〔李程远〕

高楼的性能工程实战课 -〔高楼〕

B端产品经理入门课 -〔董小圣〕

AI大模型系统实战 -〔Tyler〕

Midjourney入门实践课 -〔Jovi〕

好记忆不如烂笔头。留下您的足迹吧 :)