【问题标题】:Data from server to client in NodeJS expressNodeJS express中从服务器到客户端的数据
【发布时间】:2018-05-01 06:28:24
【问题描述】:

我是 NodeJS 的新手。 我想执行一个任务,HTML 提交按钮 POST 数据到服务器 下面是HTML代码,

<form action="/Device_Data" method="post">
  <select name="deviceSelect" id="deviceSelect" class="selectdevice" type = "text" style="margin-top:1.5%">
    <option value="" selected="selected">Choose Device</option>
    <option value="Device1">Device 1</option>
    <option value="Device2">Device 2</option>
    <option value="Device3">Device 3</option>
    <option value="Device4">Device 4</option>
    <option value="Device5">Device 5</option>
    <option value="Device6">Device 6</option>
    <option value="Device7">Device 7</option>
    <option value="Device8">Device 8</option>
  </select>
  <button id="Import" value="Import" class="button1" type="submit" >Import</button>
</form>

服务器收到 req.body 中的数据。

app.post("/Device_Data", function (req, res) {      
  console.log("Got response: " + res.statusCode);

  // result.entries contains entities matching the query
  res.setHeader('Content-Type', 'application/json');
  //console.log(req.body.deviceSelect);

  var deviceSelected = (req.body.deviceSelect);
  console.log(deviceSelected);

  var devData = ["deviceId","trainId", "messageId"];

  //var devData = [];
  var text = JSON.stringify(response.body);
  var obj = JSON.parse(text);
  res.write("Hello");
});

现在我的问题是, 我如何将字符串的 devData 数组从服务器发送到我的客户端,应该是什么代码?

提前致谢。

【问题讨论】:

  • 暂时没有使用 express - 但我认为你可以这样做 res.write(JSON.stringify(devData)); - 这会将你的 devData 数组作为 JSON 返回。这是你想做的吗?
  • 我希望该数据显示在我的网页上,与我发布数据的网页相同。我正在使用 ajax 调用,如下所示,$.ajax({ url: '/Device_Data', type: 'POST', crossDomain:true, data: {}, success: function (data) { alert("Data length is " + data.length); }, 错误:函数 () { alert("Error"); } });

标签: javascript jquery node.js ajax post


【解决方案1】:

根据express文档,使用res.json发送json数据作为请求应答。

res.status(200).json(devData);

文档示例:

res.json(null);
res.json({ user: 'tobi' });
res.status(500).json({ error: 'message' });

【讨论】:

  • 我的 AJAX 调用如下所示,$.ajax({ url: '/Device_Data', type: 'POST', crossDomain:true, data: {}, success: function (data) { alert ("数据长度为" + data.length); }, error: function () { alert("Error"); } });
  • error: function (err) { console.log(err); } }) 显示错误
  • 好吧,做一个console.log(JSON.stringify(err));
  • {"readyState":4,"responseText":"Internal Server Error\n","status":500,"statusText":"Internal Server Error"} 现在显示
猜你喜欢
  • 2022-01-12
  • 2020-08-17
  • 2015-03-05
  • 2020-08-11
  • 2016-03-19
  • 1970-01-01
  • 2015-07-09
  • 2020-04-16
  • 2015-02-08
相关资源
最近更新 更多