如何在 Meteor 中将数据从客户端发送到服务器?

我正在开发一个应用程序,但遇到了一个问题。我在“./public”文件夹中有 HTML 页面。在“./public/js”中,我有一个脚本,可以在填写此页面上的表格后收集一些数据。然后我需要将这些数据发送到服务器,服务器将使用这些数据进行一些计算。在该服务器应该发回数据之后,我可以将其显示在 HTML 结果页面上。我的想法是我需要对客户端隐藏此代码。


有什么想法可以做到吗?


编辑:知道如何实现它。


在 server/main.js 中我有 WebApp.connectHandlers。我也使用 connect-route 包。所以我需要在 public/example.js 中创建 post xhr 并将值放入其中。url 应该与 router.get('/someurl', .....) 中的 '/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) {...});

可能我对它的看法不对,但还没有发现它是如何工作的。那我现在能做什么?


牧羊人nacy
浏览 91回答 2
2回答

料青山看我应如是

https://docs.meteor.com/api/methods.htmlMeteor.call("yourMethodName", (err, result) => {  // Put your code to update HTML with result});如果您想使用 Meteor.call,将您的 html 放在公用文件夹中也可能是个坏主意。

SMILET

我已经解决了这个问题并解决了它。在 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 post 请求。它是这样的:const xhr = new XMLHttpRequest();xhr.open('post', '/method/example');xhr.send(data);xhr.addEventListener("load", () => {    const reqResult = xhr.responseText;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript