如何在ExpressJS中使用Q的承诺?

我需要生成PDF文档。 关于pdf进入generateDoc函数的所有魔法,它们以Buffer数据作为参数返回promise。 但Express不会将数据发送到客户端,只有标题。 我究竟做错了什么?

 app.get('/', function(req, res) { generateDoc().then(function(data) { res.set({ 'Content-Type': 'application/pdf', 'Content-Length': data.length }); res.end(data); }); }); 

解答

如果你想从服务器pdf返回,你必须使用res.end的binary参数。

 generateDoc().then(function(data) { res.set({ 'Content-Type': 'application/pdf', 'Content-Length': data.length }); res.end(data, 'binary'); }).fail(function (error) { res.end(500, "Some error"); }); 

尝试使用res.send ( ref ):

 app.get('/', function(req, res) { generateDoc().then(function(data) { ... res.send(data); }); }); 

我使用这个:

 server.get('/item/:id', function (req, res, next) { service.get(req.params.id). done(res.json.bind(res), next); }); 

调用done方法来执行promise链。 使用nextcallback函数作为error handling程序,以便将错误发送到客户端! 确保将json方法绑定到res对象以防止出现错误。