NiLL
NiLL

Reputation: 13853

How to use Q promises in ExpressJS?

I need to generate pdf docs. All magic about pdf going in generateDoc func which return promise with Buffer data as a param. But Express doesn't send data to the client, only header. What am I doing wrong?

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

Upvotes: 2

Views: 1482

Answers (3)

Elmer
Elmer

Reputation: 9437

I use this:

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

Call the done method to execute the promise chain. Use the next callback function as an error handler so that the error gets sent to the client! Be sure to bind the json method to the res object to prevent an error.

Upvotes: 0

NiLL
NiLL

Reputation: 13853

Solution:

If you want to return from server pdf, you must use binary param for res.end.

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");
});

Upvotes: 2

krasu
krasu

Reputation: 2037

Try to use res.send (ref):

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

Upvotes: 1

Related Questions