express mysql返回json,使用Mysql的Express使用JSON输出

I have Created a database in mysql

mysql> SELECT * FROM test456;

+-----+-------+-------------------------+

| _id | name | image |

+-----+-------+-------------------------+

| 1 | Chris | /home/images/index.jpeg |

+-----+-------+-------------------------+

1 row in set (0.00 sec)

and My Express program is below

var express = require('express')

, http = require('http')

, mysql = require('mysql'); //

var app = express();

var connection = mysql.createConnection({

host: 'localhost',

user: 'root',

password: "root",

database: 'test123'

});

connection.connect(); //

// 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'));

});

Output::

[{"_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]}]

Clearly you can see that i am not able to generate the image url instead i am generating hexadecimal number ...... how to make the hexadecimal number to a url

My research shows that i need to use base64 encoding

but how can i apply that here

any ideas

解决方案

The output is probably because each image is a Buffer rather than a String.

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

You may need to alter the character set in MySQL to UTF-8 for compatibility with Node.js:

ALTER TABLE test456 CONVERT TO CHARACTER SET utf8;

But, you can also specify a replacer with JSON.stringify():

response.end(JSON.stringify(rows, function (key, value) {

if (Buffer.isBuffer(value)) {

return value.toString();

} else {

return value;

}

}));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值