【问题标题】:How to send data from my node script to a function in the client script如何将数据从我的节点脚本发送到客户端脚本中的函数
【发布时间】:2019-08-27 02:11:15
【问题描述】:

我正在尝试通过构建自己的库存管理系统来学习 Node.JS。我正在尝试学习如何将数据从 HTML 页面和客户端 JS 脚本传递到服务器,然后将数据返回到客户端 JS 脚本。

到目前为止,我已经使用表单创建了一个基本的 HTML 页面,我创建了一个客户端 JS 脚本和索引/服务器 JS 脚本。服务器是节点,使用 nedb 作为数据库,使用 webpack。

我当前的问题是我无法获取从 HTML 表单发送到服务器的数据以转到 Client.js 函数。我尝试过使用 response.sendFile 和其他一些响应。命令,但服务器一直说 response.x 不是函数(x 是 sendfile/render/etc...)。我不确定我做错了什么,我已经包含了 HTML 表单、服务器脚本和客户端函数。

HTML

<div>
    <form action='/inventory' method='POST'>
           <input type="text" name='Name' value="Name"/>
           <input type="text" name='Model-Num' value="Model Number"/>
           <input type="text" name='Current-Stock' value="Current Stock Amount"/>
           <input type="text" name='Target-Stock' value="Target Stock"/>
           <input type="text" name='Reorder-Amount' value="Reorder Amount"/>


            <input type="submit" value="Submit"/> 
    </form>

</div>

===============================

服务器

app.post('/inventory', urlencodedParser ,(req, response, next) => {

  console.log('Im not broken');

  console.log("I got a req");
  console.log(req.body)

  response = {
      status: "success",
      code : 200,
      hype : "SO hyped",
  }

  console.log("res" , response);

  next();


});

========================

客户

function printHTML(e)
{
    console.log("e " , e);
}

我只是想让节点函数中的数据对象转到客户端函数。

【问题讨论】:

  • 感谢大家的回复,我修复了响应问题,但仍然不知道如何将 JSON 对象传递给我的客户端函数

标签: javascript node.js express ecmascript-6


【解决方案1】:

你需要 response.status(200).json(yourobject)。路由处理程序中不需要 next()。

【讨论】:

    【解决方案2】:

    一个主要问题是,您无法在客户端 Javascript 中接收来自服务器的响应。

    您以前听说过AJAX 吗?如果没有,那就看看吧。使用 AJAX,您可以进行服务器调用并从服务器获取响应。在您当前的代码中,您无法接收服务器响应。

    另外,你有参数response,然后是以后

    response = {
        status: "success",
        code : 200,
        hype : "SO hyped",
    }
    

    覆盖参数。这样,response 不再具有参数(render、sendFile 等)的功能,而是您定义的对象的功能。因此,绝对有必要重命名参数或对象。

    【讨论】:

    • 问题:将表单中的信息发送到客户端脚本中的函数,然后捆绑到获取然后发送到服务器,这是一种糟糕的设计吗?
    【解决方案3】:

    您正在覆盖您的响应对象,该对象是从路由处理程序作为参数传递的。尝试使用不同的变量名,以免覆盖它。

    app.post('/inventory', urlencodedParser, (req, response, next) => {
      console.log('Im not broken');
      console.log("I got a req");
      console.log(req.body);
    
      const returnToClient = {
        status: "success",
        code: 200,
        hype: "SO hyped"
      };
    
      // You could also use response.send() here, but your response is an 
      // object so it's better to use response.json()
      response.json(returnToClient);
    });
    

    此外,如果您将响应发送回客户端,那么您实际上不需要使用 next() 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-09
      • 1970-01-01
      相关资源
      最近更新 更多