简体   繁体   中英

Node.js timeout with requestify POST

Im trying to request a status of a user, with a POST from node.js to a PHP file. My issue is that the webservice Im calling is VERY slow to reply(4 sec), so I think the .then finishes before the 4 sec, and therefore returns nothing. Got any idea if i can extend the time for the request?

requestify.post('https://example.com/', {
              email: 'foo@bar.com'
            })
            .then(function(response) {
                var answer = response.getBody();
                console.log("answer:" + answer);
            });

I am not that knowledgeable on requestify but are you sure you can use post to a https address? In the readme only requestify.request(...) uses a https address as an example. ( see readme )

One tip I can definitely give you though is to always catch your promise:

 requestify.get(URL).then(function(response) { console.log(response.getBody()) }).catch(function(err){ console.log('Requestify Error', err); next(err); }); 

This should at least give you the error of your promise and you can specify your problem.

Each call to Requestify allows you to pass through an Options object, the definition of that object is described here: Requestify API Reference

You are using the short method for POST, so I'll show that first, but this same syntax will work for put as well, notice that get , delete , head do not accept a data argument, you send url query parameters through the params config property.

requestify.post(url, data, config)
requestify.put(url, data, config)
requestify.get(url, config)
requestify.delete(url, config)
requestify.head(url, config)

Now, config has a timeout property

timeout {number}

Set a timeout (in milliseconds) for the request.

So we can specify the a timeout of 60 seconds with this syntax:

var config = {};
config.timeout = 60000;
requestify.post(url, data, config)

or inline:

requestify.post(url, data, { timeout: 60000 })

So lets put that together now into your original request:

as @Jabalaja pointed out, you should catch any exception messages, however you should do this with the error argument on the continuation. ( .then )

requestify.post('https://example.com/', {
    email: 'foo@bar.com'
}, {
    timeout: 60000
})
.then(function(response) {
    var answer = response.getBody();
    console.log("answer:" + answer);
}, function(error) {
    var errorMessage = "Post Failed";
    if(error.code && error.body)
        errorMessage += " - " + error.code + ": " + error.body
    console.log(errorMessage);
    // dump the full object to see if you can formulate a better error message.
    console.log(error);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM