直接上代码
var resu;
var db = require("./dbs.js");
var http=require("http");
var server=http.createServer(function(req,res){
if(req.url!=="/favicon.ico"){
resu = db.searchDb();
res.writeHead(200,{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"});
res.write(resu);
}
res.end();
});
server.listen(1338,"localhost",function(){
console.log("开始监听...");
});
这个是数据库查询的文件
exports.searchDb =function(){
var Mysql = require('node-mysql-promise');
var mysql = Mysql.createConnection({
host: 'dm191867.my3w.com',
user: 'dm191867',
password: '123',
// database:'dm191867_db',
});
//SELECT * FROM table;
mysql.table('SalesInfo').field('OrderNO,OrderDate,CustomID,Quantity,Money,OrderStatus').select().then(function (data) {
return data;
console.log(data);
}).catch(function (e) {
console.log(e);
});
}
报错信息
_http_outgoing.js:439
throw new TypeError('first argument must be a string or Buffer');
^
TypeError: first argument must be a string or Buffer
at ServerResponse.OutgoingMessage.write (_http_outgoing.js:439:11)
at Server.<anonymous> (c:\Users\lenovo\WebstormProjects\bootstrap\myserver.js:8:13)
at emitTwo (events.js:87:13)
at Server.emit (events.js:172:7)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:528:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:88:23)
按照大神的方法改好了,但是遇到了新的问题。我现在mysql.query('XXXXXX')中的sql句是固定的。我想动态生成不同的sql语句,就在searchDb的参数里加了个sqldata。
代码如下:
exports.searchDb =function (sqldata,resultCallback){
var Mysql = require('node-mysql-promise');
var mysql = Mysql.createConnection({
host: 'qdm19.my3w.com',
user: 'qdm19',
password: '123E',
database:'qdm19_db',
});
//SELECT XX FROM table;
mysql.query('SELECT DISTINCT %s,%s,%s,%s,%s,%s FROM %s WHERE %s',sqldata).then(function (data)
{
console.log(data);
resultCallback(null,data);
}).catch(function (e) {
console.log(e);
resultCallback(e);
});
}
其中sqldata是个数组
var sqldata=
[
'OrderNO',
'DATE_FORMAT( OrderDate , "%Y-%m-%d")OrderDate',
'c.CustomName',
'(select count(Quantity) from SalesInfo where OrderNo=s.OrderNO)Quantity',
'(select sum(Money) from SalesInfo where OrderNo=s.OrderNO)Money',
'OrderStatus',
'SalesInfo as s left join Customer as c on s.CustomID=c.CustomNo',
'1=1'
]
换成这种形式以后 第一次查询是没有问题的 再点一次查询就会报错说sql句有问题。。
数据库查询
学习一下async库
return 的数据在回调函数中、传回来应该是undefined吧、可以把回调传进去、
虽然我没用过,但是你应该把promise返回吧?
然后