在Node.js

时间:2016-02-06 13:16:48

标签: javascript php mysql node.js

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

+----+---------+
| 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结果的方法?似乎没有绑定结果函数....

1 个答案:

答案 0 :(得分:0)

可以像处理 Javascript 数组一样对待rows对象。您只需创建一个转换后的输出:

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});