场景: 我需要在nodejs中调用一个处理时间较长的接口吗,可能会超过120s。
nodejs 默认的 http 请求超时时间超过120s,则会返回超时。
问题:
如何修改默认的超时时间呢?
最好是针对某个请求修改,不要影响到其他请求。
Koa示例:
router.get('/list', async (ctx) => {
// 设置处理过程超过120s
let data = await timeoutService(121000)
ctx.status = 200;
ctx.body = {
success: true,
data: data
};
});
使用nodejs调用
// nodejs 调用
const GetList = (data) => {
return new Promise((resolve, reject) => {
let bs = JSON.stringify(data)
console.log(bs)
let encode = new Buffer(bs).toString('base64')
let postData = JSON.stringify({ data: encode})
var opt = {
method: 'GET',
host: 'localhost',
port: 3100,
path: '/list',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
'Accept': 'application/json; charset=utf-8'
}
}
function getTimeLast(label, startTime) {
let finishTime = Date.now()
let last = (finishTime - startTime) / 1000
console.log(`${label} ${last}`)
}
let startTime = Date.now()
GetList({a: 1}).then(res => {
console.log(res)
getTimeLast('成功返回用时:', startTime)
}).catch(e => {
console.log(e)
getTimeLast('失败返回用时:', startTime)
})
结果返回如下:
{"a":1}
{ Error: socket hang up
at createHangUpError (_http_client.js:331:15)
at Socket.socketOnEnd (_http_client.js:423:23)
at emitNone (events.js:111:20)
at Socket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1055:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9) code: 'ECONNRESET' }
请求遇到问题:socket hang up
socket hang up
失败返回用时: 120.018
弑天下
相关分类