首页 > 解决方案 > 如何将数据从我的节点脚本发送到客户端脚本中的函数

问题描述

我正在尝试通过构建自己的库存管理系统来学习 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);
}

我只希望节点函数中的数据对象转到客户端函数。

标签: javascriptnode.jsexpressecmascript-6

解决方案


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


推荐阅读