【问题标题】:how do i group Nodejs MYSQL related tables as JSON and send result to the client?如何将 Nodejs MYSQL 相关表分组为 JSON 并将结果发送到客户端?
【发布时间】:2019-07-20 02:34:01
【问题描述】:

我想将 Mysql 相关表作为 JSON From NodeJS 发送回客户端。 像这样的例子: 我有学生表和学生国家表。 其中学生表具有名为 country_id 相关国家表的字段。 最后我想要的是返回客户端。

所有学生信息,学生国家分配到字段命名国家

   //this is poth tables
   SELECT * FROM students s;
   SELECT * FROM country;

我希望每个学生表和国家/地区表都重新格式化

   students = [
    {
      studentId: 1,
      studentName: 'Tusbahle',
      country: {
        id: 1,
        country: 'Somalia'
      }
    },
    {
      studentId: 2,
      studentName: 'Alex',
      country: {
        id: 1,
        country: 'UK'
      }
    }
  ]

任何帮助。

【问题讨论】:

  • 您可以使用JSON.stringify(object) 并将其作为响应从您的节点后端通过订阅的服务发送到前端..

标签: javascript node.js


【解决方案1】:

我相信你的 SQL 语句应该是这样的:

SELECT s.student_id, s.student_name, s.country_id, c.country_name
FROM students s
INNER JOIN country c 
ON s.country_id = c.id;

(我假设您的数据在数据库中表示为您发送的 JSON)。如果没有:请随意更换(c.country_name、c.id、s.student_name 等)

接下来你真正需要做的就是:

我更新了返回关键字..

students = rows.map(row => {
return {
    studentId: row.student_id,
    studentName: row.student_name,
    country:{
        id: row.country_id,
        country: row.country_name
    }
}
})

【讨论】:

  • 谢谢,我不知道我是怎么错过的
【解决方案2】:

如果您使用的是 express 路由,那么您可以通过这个将数据从 nodejs 发送到该路由 “变量”这将包含表的数据 res.render('page.html', {data:variable}); 您可以像这样访问 html 模板中的数据变量 如果这是数组

{% for obj in data %}
   // use this
{% endfor %}

它会工作,但如果你使用的是模板引擎,如果你不是,那么在路由之前添加 swig 或其他类似的模板引擎

const swig = require('swig')
app.engine('html', swig.renderFile);
app.set('view engine', 'html');

【讨论】:

  • 先生,这不是我要找的。我根据需要编辑了我的问题
  • 好的,现在我知道了,你怎么称呼客户端?或者您使用快速路由作为客户端网址?
  • 快速路由 router.post("/students",(req,res,next)=>{ /.... }) 。和客户角度
猜你喜欢
  • 2021-10-07
  • 1970-01-01
  • 2020-02-28
  • 2014-04-05
  • 2017-08-15
  • 1970-01-01
  • 2018-07-01
  • 1970-01-01
  • 2018-01-21
相关资源
最近更新 更多