2

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

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

我的快递程序如下

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 编码,但我如何在这里应用它

有任何想法吗

4

1 回答 1

1

输出可能是因为 eachimage是 aBuffer而不是 a String

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

您可能需要将MySQL 中的字符集更改为 UTF-8 以与 Node.js 兼容:

ALTER TABLE test456 CONVERT TO CHARACTER SET utf8;

但是,您也可以指定一个replacerwith JSON.stringify()

response.end(JSON.stringify(rows, function (key, value) {
    if (Buffer.isBuffer(value)) {
        return value.toString();
    } else {
        return value;
    }
}));
于 2013-09-17T06:55:56.900 回答