簡體   English   中英

如何在 Meteor 中將數據從客戶端發送到服務器?

[英]How to send data from client to server in Meteor?

我正在開發一個應用程序,但遇到了一個問題。 我在“./public”文件夾中有 HTML 頁面。 在“./public/js”中,我有一個腳本,它在填寫此頁面上的表單后收集一些數據。 然后我需要將這些數據發送到服務器,在那里將使用這些數據進行一些計算。 在此服務器應該將數據發回之后,以便我可以在 HTML 結果頁面上顯示它。 這個想法是我需要對客戶端隱藏此代碼。

任何想法如何做到?

編輯:知道如何實現它。

在 server/main.js 我有 WebApp.connectHandlers。 我也使用連接路由包。 所以我需要在 public/example.js 中創建 post xhr 並將值放入其中。 url 應該是 '/someurl' 和 router.get('/someurl', .....) 一樣,對吧? 如何正確完成?

這是我現在擁有的 server/main.js 中的一些代碼:

    WebApp.connectHandlers.use(connectRoute(function (router) {
      router.get('/example', staticFile(process.cwd() + '/../web.browser/app' + 'example.html'))

問題是我從 example.html 中的表單中獲取一些值,.js 文件存儲在 /public 中。 然后我創建 xhr post 請求並指出應該作為 server/main.js 中 router.get() 中的第一個 arg 的 url。

/public/example.js 代碼片段:

    const values = document.querySelector("input").value  //example of some data from form
    const xhr = new XHRHttpRequest()
    xhr.open('POST', '/someurl')
    xhr.send(values)

現在我需要在 server/main.js 中獲取這個請求,但是我不能在一個 url 上使用 router.get('/example',.....) 兩次。 我的意思是它不會像這樣工作:

    WebApp.connectHandlers.use(connectRoute(function (router) {
      router.get('/example', staticFile(process.cwd() + '/../web.browser/app' + 'example.html'))
      router.get('/example', (req, res, next) {...});

可能我不正確,但還沒有發現它是如何工作的。 那我現在能做什么?

https://docs.meteor.com/api/methods.html

Meteor.call("yourMethodName", (err, result) => {
  // Put your code to update HTML with result
});

如果您想使用 Meteor.call,將 html 放在公共文件夾中也可能是一個壞主意。

我已經解決了這個問題並解決了它。 在 server/main.js 中,我添加了以下代碼:

router.post('/method/example', (req, res, next) => {
    let data = '';
    req.on("data", chunk => {
      data += chunk;
    });
    req.on('end', () => {
      const result = dataHandler(data);
      res.write(`${result}`);
      res.end();
    });
}

在 /public/example.js 中,我剛剛使用與 server/mains.js 中的新行中相同的 URL 進行了 xhr 發布請求。 這是它的樣子:

const xhr = new XMLHttpRequest();
xhr.open('post', '/method/example');
xhr.send(data);
xhr.addEventListener("load", () => {
    const reqResult = xhr.responseText;
}

暫無
暫無

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

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