user9760741
user9760741

Reputation:

NodeJs app "hanging" or "freezing" whenever an error occurs

When I make multiple post requests to my nodejs server and all of the parameters are correct, everything works fine (and doesnt freeze) but when I make multiple post requests with incorrect parameters that gives an error, my nodejs server just freezes/hangs for a few minutes. Why is this?

Here is my code btw

app.post('/pushtransaction', function(req, res) {
    console.log(req.body);
    console.log(5);
    if (req.body.sigs) {
        let sigver = xmf.modules.ecc.Signature.from(req.body.sigs).toString();
        let lasig = [sigver];
        console.log(req.body.packedTr);
        let transi = JSON.parse(req.body.packedTr);

        //let sigver = req.body.sigs;
        let package = {
            compression: 'none',
            transaction: transi,
            signatures: lasig
        }

        console.log(package);
        //Pushes tx in correct format
        xmf.pushTransaction(package).then(result=>{
            res.send(result);
            res.end();
            console.log(result);
        }).catch(err => {
            console.log(err)
        });
    }
})

Upvotes: 2

Views: 5993

Answers (3)

Shishir Arora
Shishir Arora

Reputation: 5923

Adding to other answers, you can add a middleware for timeouts, if any service fails to respond in some time, like

var timeout = require('connect-timeout');
app.use(timeout('5s'));

Upvotes: 0

hot.chai.latte
hot.chai.latte

Reputation: 41

When your error is encountered, your Node server does not know what to do other than console.log() the error. It needs to end that request and send some response. You can res.status(400).send({ error: err }) when you're within the catch.

Upvotes: 4

user3210641
user3210641

Reputation: 1631

Make sure res.send() method gets called every time in your request.

Updated Javascript:

app.post('/pushtransaction', function(req, res) {
    console.log(req.body);
    console.log(5);
    if (req.body.sigs) {
        let sigver = xmf.modules.ecc.Signature.from(req.body.sigs).toString();
        let lasig = [sigver];
        console.log(req.body.packedTr);
        let transi = JSON.parse(req.body.packedTr);

        //let sigver = req.body.sigs;
        let package = {
            compression: 'none',
            transaction: transi,
            signatures: lasig
        }

        console.log(package);
        //Pushes tx in correct format
        xmf.pushTransaction(package).then(result=>{
            res.send(result);
            res.end();
            console.log(result);
        }).catch(err => {
            console.log(err);
            res.status(400).send();
        });
    }

    res.status(400).send();
})

Additionally you don't have to call res.end() if you call res.send(). see Must res.end() be called in express with node.js?

Upvotes: 0

Related Questions