JSON输出使用Express使用Mysql

我已经在MySQL中创build了一个数据库

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

我的快车scheme如下

 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,而不是我生成hex数字……如何使hex数字的url

我的研究表明,我需要使用base64编码,但我怎么能在这里应用

有任何想法吗

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

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

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

 ALTER TABLE test456 CONVERT TO CHARACTER SET utf8; 

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

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