Search code examples
javascriptnode.jsajaxmeteorserver

How to send data from client to server in Meteor?


I'm working on one app and have faced one problem. I have HTML page in './public' folder. In './public/js' I have a script that collects some data after filling the form on this page. Then I need to send this data to a server, where some calculations with this data will be done. After this server should send the data back so I can display it on HTML result page. The idea is that I need to hide this code from the client.

Any ideas how it can be done?

EDIT: Got an idea how it can be realized.

In server/main.js I have WebApp.connectHandlers. Also I use connect-route package. So I need to create post xhr in public/example.js and put values in it. the url should be '/someurl' the same as in router.get('/someurl', .....), right? How can it be done correctly?

Here's some code from server/main.js what I have now:

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

The thing is I get some values from form in example.html with .js file stored in /public. Then I create xhr post request and indicate url that should go as the first arg in router.get() in server/main.js.

Fragment of /public/example.js code:

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

And now I need to get this request in server/main.js, but I can't use router.get('/example',.....) twice on one url. I mean it won't work like this:

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

Probably I'm not right about it but haven't found out yet how it works. So what can I do now?


Solution

  • I've worked on this problem and solved it. In server/main.js I add this code:

    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();
        });
    }
    

    And in /public/example.js I just did an xhr post request with the same URL as in new line in server/mains.js. And here's how it looks like:

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