【问题标题】:Modify MySQL result on Node.js在 Node.js 上修改 MySQL 结果
【发布时间】:2016-02-06 13:16:48
【问题描述】:

我正在构建 API 来为用户提供文件链接。 数据库正在存储文件 ID 和文件名。并且所有文件都存储在同一个目录中。

+----+---------+
| ID |  File   |
+----+---------+
| 01 | abc.jpg |
| 02 | cde.mp3 |
| 03 | efg.doc |
+----+---------+

当我使用 php 构建 API 时

 $sql = "SELECT id,file FROM `test’";
 if($stmt=$conn->prepare($sql)) {
   $stmt->execute();
   $stmt->bind_result($id, $file);
   $array = array();

   while ($stmt->fetch()) {
     $array[] = array('id' =>$id, 'path'=>'http:// abc.com/file/' . $file);
   }

   $json = json_encode($array, JSON_UNESCAPED_UNICODE);
 } else {
 }

 print_r($json);

我可以绑定结果并修改它们。那么结果会是这样的

[{"id": "01", "path": "http:// abc.com/file/abc.jpg"}, 
{"id": "02", "path": "http:// abc.com/file/cde.mp3"}, 
{"id": "03", "path": "http:// abc.com/file/efg.doc"}]

现在,我要通过 Node.js 重新构建它,我找到了一个教程here

node.js上输出的代码是这样的

 res.json({"Error" : false, "Message" : "Success", "Users" : rows}

有什么方法可以修改 nodejs 上的结果?好像没有绑定结果函数....

【问题讨论】:

    标签: javascript php mysql node.js


    【解决方案1】:

    rows 对象可以被视为 Javascript 数组。您只需要创建一个转换后的输出:

    var users = []; // This will hold the transformed output
    
    for (var user in rows) {
      // Modify the file property
      user.file = 'some path' + user.file;
      // Add the transformed user to the 'users' array
      users.push(user);
    }
    
    res.json({"Error" : false, "Message" : "Success", "Users" : users});
    

    【讨论】:

      猜你喜欢
      • 2019-03-11
      • 2014-08-01
      • 2019-02-15
      • 2010-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 2016-08-05
      相关资源
      最近更新 更多