【问题标题】:JSON output using Express using Mysql使用 Mysql 使用 Express 的 JSON 输出
【发布时间】:2013-09-21 11:31:05
【问题描述】:

我已经在mysql中创建了一个数据库

mysql> SELECT * FROM test456;
+-----+-------+-------------------------+
| _id | name  | image                   |
+-----+-------+-------------------------+
|   1 | Chris | /home/images/index.jpeg |
+-----+-------+-------------------------+
1 row in set (0.00 sec)

我的 Express 程序在下面

var express = require('express')
  , http = require('http')
  , mysql = require('mysql'); // <---- HERE

var app = express();

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: "root",
    database: 'test123'
});

connection.connect(); // <---- AND HERE

// all environments
app.set('port', process.env.PORT || 7005);


app.get('/',function(request,response){
connection.query('SELECT * FROM test456', function(err, rows, fields)

   {
            console.log('Connection result error '+err);
            console.log('no of records is '+rows.length);
                    response.writeHead(200, { 'Content-Type': 'application/json'});
            response.end(JSON.stringify(rows));
    });

} );



http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

输出::

[{"_id":1,"name":"Chris","image":[47,104,111,109,101,47,105,109,97,103,101,115,47,105,110,100,101,120,46,106,112,101,103]}]

很明显,您可以看到我无法生成图像 url,而是生成十六进制数......如何将十六进制数转换为 url

我的研究表明我需要使用 base64 编码 但是我如何在这里应用它

任何想法

【问题讨论】:

    标签: mysql node.js express


    【解决方案1】:

    输出可能是因为每个image 都是Buffer 而不是String

    console.log(Buffer.isBuffer(rows[0].image)); // true
    

    您可能需要在 MySQL 中将alter the character set 转为 UTF-8 以与 Node.js 兼容:

    ALTER TABLE test456 CONVERT TO CHARACTER SET utf8;
    

    但是,您也可以使用JSON.stringify() 指定replacer

    response.end(JSON.stringify(rows, function (key, value) {
        if (Buffer.isBuffer(value)) {
            return value.toString();
        } else {
            return value;
        }
    }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 1970-01-01
      相关资源
      最近更新 更多