selanac82
selanac82

Reputation: 3000

Why does settimeout break Expressjs

I have the following code in express.js

// POST api/posts/:id
exports.post = function(req, res){

    req.body[0].id = posts.length + 1;
    posts.push(req.body[0]);
    console.log(posts);
    fs.writeFileSync("json/posts.json", JSON.stringify(posts));
    setTimeout(function(){
        res.set.apply(res, utils.contentType);
        res.json(req.body[0]);
    }, utils.randomNumberBetween(1000, 3000));


};

When I post a simple json object I receive the following error.

org.apache.http.NoHttpResponseException: localhost:9000 failed to respond

If I remove the settimeout everything works as expected. I have used settimeout in other places like so:

// GET api/posts
exports.get = function(req, res){
    setTimeout(function(){
        res.set.apply(res, utils.contentType);
        res.json(posts);
    }, utils.randomNumberBetween(1000, 3000));
};

So I'm not understanding why it would break when posting. Any thoughts??

Upvotes: 3

Views: 150

Answers (1)

Dennis
Dennis

Reputation: 4017

This is because the application making the request expects a response from express within a certain amount of time, say 5 seconds. If it does not receive anything back it thinks something went wrong. One thing you can do to resolve this is change the amount of time your "sending/requesting" application waits/listens for a response.

Upvotes: 2

Related Questions