Node.js超时,请求开机自检



我试图请求用户的状态,从节点.js发布到PHP文件。 我的问题是 Web 服务 Im 调用的回复速度非常慢(4 秒),所以我认为 .then 在 4 秒之前完成,因此不返回任何内容。知道我是否可以延长请求的时间吗?

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

我对请求不是很了解,但你确定你可以使用 post 到 https 地址吗?在自述文件中,只有requestify.request(...)使用https地址作为示例。(见自述文件)

不过,我绝对可以给你的一个提示是始终兑现你的承诺:

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

这至少应该给你承诺的错误,你可以指定你的问题。

每次调用 Requestify 都允许您传递一个Options对象,该对象的定义如下所述: 请求 API 参考

您正在对 POST 使用short方法,所以我将首先展示这一点,但同样的语法也适用于put,请注意,getdeletehead不接受数据参数,您通过paramsconfig 属性发送 url 查询参数。

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

现在,config拥有timeout房产

超时{数字}

设置请求的超时(以毫秒为单位)。

因此,我们可以使用以下语法指定 60 秒的超时:

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

或内联:

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

因此,现在让我们将其放在原始请求中:

正如@Jabalaja指出的,您应该捕获任何异常消息,但是您应该使用延续上的错误参数执行此操作。 (.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);
});

最新更新