2014-10-30 113 views
0

我試圖使用Meteor的(v1.0)HTTP.call方法與基於Python的服務器進行通信,該服務器只接受頭文件中的application/json內容類型但從客戶端調用API URL時,我無法在Meteor中正確設置HTTP標頭。在客戶端的HTTP.call中設置「Content-Type」頭文件流星

有了這樣一個片段,我從Python的服務器415 (Unsupported Media Type)錯誤:

if (Meteor.isClient) { 
    Template.testing.events({ 
    'click button': function(event, tpl) { 
     event.preventDefault(); 

     var method = 'GET'; 
     var url = 'http://localhost:6543/test'; 
     var options = { 
     headers: {'Content-Type': 'application/json'} 
     } 

     HTTP.call(method, url, options, function(error, result) { 
     if (error) { 
      console.log('ERRR'); 
      console.log(error); 
     } else 
      console.log('RESULT'); 
      console.log(result); 
     }); 
    } 

    }); 
} 

但是,如果我叫從服務器端相同的URL流星像這樣:

if (Meteor.isClient) { 
    Template.testing.events({ 
    'click button': function(event, tpl) { 
     event.preventDefault(); 

     var method = 'GET'; 
     var url = 'http://localhost:6543/test'; 
     var options = { 
     headers: {'Content-Type': 'application/json'} 
     } 

     Meteor.call('APICall', method, url, options, function (error, result) { 
     if (error) { 
      console.log('CLIENT ERRR'); 
      console.log(error); 
     } else { 
      console.log('CLIENT RESULT'); 
      console.log(result); 
     } 
     }); 
    } 

    }); 
} 

if (Meteor.isServer) { 
    Meteor.methods({ 
    APICall: function (method, url, options) { 
     HTTP.call(method, url, options, function(error, result) { 
     if (error) { 
      console.log('SERVER ERRR'); 
      console.log(error); 
     } else 
      console.log('SERVER RESULT'); 
      console.log(result); 
     }); 
    } 
    }); 
} 

我從服務器得到了正確的迴應。

在Python方面,我爲所有可能的請求啓用了CORS起源(例如cors_origins=('*'))。

所以...是可以在客戶端設置標題,還是應該始終從服務器端調用此服務?

回答

0

我從來沒有在客戶端任何成功,但它應該。退房流星HTTP包的HTTP.call客戶端部分:

https://github.com/meteor/meteor/blob/devel/packages/http/httpcall_client.js

主要是它使用瀏覽器XHR對象上的客戶端可導致一系列的問題,如不兼容之類的東西。你甚至可以看到的代碼註釋中引用的(約line 136)的問題

And when you check out the server implementation你可以看到它使用了request庫(從connect),這在我的書,是非常可靠的,你可以生成均勻結果跨所有用戶(而不是圍繞瀏覽器差異跳舞)。

我的選擇和建議很明顯是服務器端調用。不僅僅是因爲它的工作原理和可靠性,它也是'更安全'的,因爲您不必向客戶端/最終用戶公開更多系統的內部運作。誰知道?也許你在基於Python的服務器上運行你的API的敏感數據。

+0

謝謝你的回答!想知道,你提到「你的書」?那是哪一個? – errata 2014-10-31 11:52:28

+1

啊! [這是一個成語](http://idioms.thefreedictionary.com/in+my+book)。雖然我希望我真的寫了一本書:) – 2014-11-01 11:17:35

+0

啊哈哈,我看到:)從來沒有聽說過迄今爲止哈哈哈哈:) – errata 2014-11-02 23:34:41