javascript - Meteor 服务器端 HTTP 请求

标签 javascript meteor meteor-blaze

我尝试构建的小型 meteor 应用程序遇到了一些问题。我有一种感觉,这是由于没有完全理解服务器与客户端关系如何运作的结果。我已经尝试让它工作几个小时,并认为这是设置它的唯一合乎逻辑的方法。补充一下我是初学者可能会有所帮助。

还值得注意的是,我在客户端发出 http 请求时运行良好。

应该发生什么:

提交表单,表单中的文本通过 http 请求发送到 API,返回、解析 JSON,并将值返回给用户(它们给出国家/地区代码,返回边框) 。除此之外,我想将每个请求存储在带有时间戳的集合中。

任何帮助将不胜感激。

这是 JS:

borders = new Mongo.Collection("borders");

if (Meteor.isClient) {
  // This code only runs on the client

  //set the session blank before submit action on form. 

  Template.hello.helpers({
    borders: function () {
      // return borders.find({});
      // return borders.find({}, {limit: 1});
      return Session.get("border");
    }
  });

  Template.body.events({
    "submit .new-task": function (event) {
      // Prevent default browser form submit
      event.preventDefault();

      // Get value from form element
      var countryCode = event.target.text.value;

      //set form element variable in the session so it can be accessed on the server
      session.set(countryCode)

      //invoke the server method
      Meteor.call("getID", function(error, results) {
        console.log(results.content); //results.data should be a JSON object
      });

    }
  });
}

//server-side code 
if (Meteor.isServer) {
      session.get(countryCode)
      var url = "http://restcountries.eu/rest/v1/alpha/"+countryCode;
    Meteor.methods({
        getID: function () {
          this.unblock();
          HTTP.get(url, {timeout:30000}, function(error, response) {
            var respJson = JSON.parse(response.content);
            console.log(respJson)
            Session.set("border",respJson["subregion"])
            // Insert a task into the collection
            borders.insert({
              text: respJson["borders"],
              createdAt: new Date() // current time
            });
            // Clear form
            event.target.text.value = "";
          });
        }
    });
}

应用程序运行时出现错误:

=> Started proxy.                             
=> Started MongoDB.                           
W20151203-17:09:54.345(-8)? (STDERR)          
W20151203-17:09:54.346(-8)? (STDERR) /Users/me/.meteor/packages/meteor-tool/.1.1.10.1evms9b++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:245
W20151203-17:09:54.347(-8)? (STDERR)                        throw(ex);
W20151203-17:09:54.347(-8)? (STDERR)                              ^
W20151203-17:09:54.347(-8)? (STDERR) ReferenceError: session is not defined
W20151203-17:09:54.347(-8)? (STDERR)     at borderApp.js:38:7
W20151203-17:09:54.347(-8)? (STDERR)     at /Users/me/Dev/Web/borderApp/.meteor/local/build/programs/server/app/borderApp.js:67:4
W20151203-17:09:54.347(-8)? (STDERR)     at /Users/me/Dev/Web/borderApp/.meteor/local/build/programs/server/boot.js:242:10
W20151203-17:09:54.347(-8)? (STDERR)     at Array.forEach (native)
W20151203-17:09:54.347(-8)? (STDERR)     at Function._.each._.forEach (/Users/me/.meteor/packages/meteor-tool/.1.1.10.1evms9b++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/server-lib/node_modules/underscore/underscore.js:79:11)
W20151203-17:09:54.347(-8)? (STDERR)     at /Users/me/Dev/Web/borderApp/.meteor/local/build/programs/server/boot.js:137:5

这是我用于前端的 HTML:

<head>
  <title>Todo List</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
</head>

<body>
  <div class="form-group">
    <header>
      <h1>Todo List</h1>

      <form class="new-task">
        <input class="input-lg form-control" type="text" name="text" placeholder="Type to add new tasks" />
      </form>
    </header>

<H3>
{{> hello}}
</h3>

  </div>
</body>

<template name="hello">
  <p>{{borders}}</p>
</template>

<template name="button">
 <button type="submit" class="btn btn-danger">Find Borders &rarr;</button>
 </template>

最佳答案

从技术上讲,您会收到错误,因为您在此处编写了 session.set(varhere) 而不是 Session.set('nameofsessionvar',newvalueforsessionvar)。然而,即使这样它也不起作用,因为 session 变量在每个客户端的基础上全局地可供客户端使用,而不是服务器。

尝试改变:

//session.set(countryCode)
Meteor.call("getID", countryCode, function(error, results) {
...
}

和:

//session.get(countryCode)
//var url = "http://restcountries.eu/rest/v1/alpha/"+countryCode;
getID: function (countrycode) {
      var url = "http://restcountries.eu/rest/v1/alpha/"+countryCode;
}

关于javascript - Meteor 服务器端 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34079395/

相关文章:

javascript - 单击子组件按钮时卸载组件//React

meteor .js : how to swap partial templates in and out of the main page

javascript - 在 javascript "object"中继承属性

javascript - Django 使用 Javascript 包含模板

javascript - 在javascript中验证英国驾驶执照正则表达式

javascript - 如何使用onclick将html中的元素数量相乘

meteor - 为什么meteor 会撤消对嵌套在观察者方法中的集合的更改?

javascript - #each 完成后如何执行回调?

javascript - 如何使用 ReactiveVar 在 Meteor 中的模板之间传递数据

javascript - Meteor 不加载外部 CSS 和 JS 文件