我在 knex.js
和 express
中遇到问题,代码如下:
userRouter.get('/:userId', function (req, res) {
DB('users').where({
id: req.params.userId
}).first('name').pipe(res);
});
正如 knex.js
文档所写:knex.js 查询有一个流接口(interface)。
但我无法将结果通过管道传递给 express(node http api)
响应。
上面的代码不起作用。
有一个“TypeError”:
TypeError: first argument must be a string or Buffer
出了什么问题?
最佳答案
创建一个流并首先将其通过管道传输到 JSONStream,最后通过管道将其传输到您的响应对象
var knex = require('knex')({
client: 'mysql',
connection: {
host : '...',
user : '...',
password : '...',
database : '...'
}
});
var JSONStream = require('JSONStream');
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = knex.select('*').from('table').limit(3);
res.set('Content-Type', 'application/json');
sql.stream().pipe(JSONStream.stringify()).pipe(res);
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
关于javascript - knex.js 管道表达,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26376454/