簡體   English   中英

流星服務器端HTTP請求

[英]Meteor Server-Side HTTP Request

我正在嘗試構建的小型流星應用程序遇到一些問題。 我有一種不完全了解服務器-客戶端關系如何工作的結果。 我試圖使其工作數小時,並將其視為設置它的唯一合乎邏輯的方法。 我可能是個初學者,這可能會有所幫助。

還值得注意的是,我在客戶端發出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;
}

您可能會誤解使用不同框架的Meteor Session MeteorSession僅在客戶端可用,而在服務器中不可用,請參閱: http : //docs.meteor.com/#/full/session

對於您的問題,可以將countryCode用作Meteor.call的參數

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

和您的服務器:

if (Meteor.isServer) {
    Meteor.methods({
        getID: function (countryCode) {
        var url = "http://restcountries.eu/rest/v1/alpha/"+countryCode;
          this.unblock();
          HTTP.get(url, {timeout:30000}, function(error, response) {
            var respJson = JSON.parse(response.content);
            console.log(respJson)

            // Insert a task into the collection
            borders.insert({
              text: respJson["borders"],
              createdAt: new Date() // current time
            });
            // Clear form
            event.target.text.value = "";
          });
        }
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM