我在node.js中编写API。
url http://localhost:8000/api/request?connId=19&timeout=8000
当我从 Postman 调用上述API时,需要8秒才能给出响应。与预期相同。
但是当从 curl 调用它时,它会立即提供输出。
curl http://localhost:8000/api/request?connId=19&timeout=8000
代码是:
app.get('/api/request', ( req, res ) => {
let timeoutID = null; // return by setTimeout
let starttime = null; // time when request is begin
const time = req.query.timeout; // time send by client
const connId = req.query.connId; // id send by client
// checking client data is valid or not
if ( typeof(connId) !== undefined && typeof(time) !== undefined ) {
starttime = new Date(); // get current time
starttime = starttime.setMilliseconds(starttime.getMilliseconds()); // convert into millisecon
// initiate setTimeout
timeoutID = setTimeout(() => {
// remove that element from global array which reqest has been complted
removeByAttr(timeout, 'connId', connId);
// res.send({ status: "ok"}); // send response
}, time);
// initiate setInterval
const setInv = setInterval(() => {
// check timeout [] conatin the current request
const arrLength = timeout.length && timeout.filter(({ connId }) => req.query.connId === connId).length;
if ( arrLength === 0 ) {
res.send({ status: "ok"}); // send response
clearInterval(setInv); // clear/destroy current Interval
}
}, 80);
// insert the current request into global [] timeout
timeout.push({
connId,
time,
timeoutID,
starttime,
'endtime': +starttime + +time
});
}
});
答案 0 :(得分:3)
正如我从您的代码中发现的那样curl tutorial that当您使用curl获取端点时,您的命令应该是这样的:
curl "http://localhost:8000/api/request?connId=19&timeout=8000"
如果网址中没有双重倒置的逗号,console.log(req.query)
将导致{ connId: '19' }
导致问题。