问题描述
我正在使用Express v4.13.4开发Node v4.2.4应用程序.现在,我想增加特定上传路由的超时时间.
I'm developing a Node v4.2.4 application using Express v4.13.4. Now I would like to increase the timeout time for a specific upload route.
根据我所阅读和经历的内容:
From what I've read and experienced:
- the default Node server timeout is 2 minutes
- a Node socket has no timeout by default
- there's middleware from Express to handle timeouts
但是,当我尝试为上传路由实现 connect-timeout 中间件时,我迷失了.
However, I'm lost when trying to implement the connect-timeout middleware for the upload route.
应用程序设置
const app = express();
app.use(cors());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: false }));
app.use(passport.initialize());
app.use('/uploads', uploadRoutes);
app.use(errorHandler);
function errorHandler(err, req, res, next) {
if (err.code && err.code === 'ETIMEDOUT') {
if (!res.headersSent) {
res
.status(408)
.send({
success: true,
message: 'Timeout error'
});
}
}
next(err);
}
const server = app.listen(config.port);
上传路线定义
router.route('/:uploadId/upload-files')
.post(timeout('3m'),
require('./actions/upload-files').prepareHandler,
require('./actions/upload-files').uploadHandler(),
require('./actions/upload-files').responseHandler);
但是,当我上传文件时,仅在命令行控制台上3分钟后,我确实从express-timeout
看到了错误.该请求仍在进行中,没有返回状态码408.
However, when uploading the files I do see the error from express-timeout
after 3 minutes ONLY in the command line's console. The request is still in progress and no status code of 408 is returned.
4分钟后,我终于看到408状态和超时错误"作为响应对象的一部分.
After 4 minutes I finally see the 408 status and 'Timeout error' as part of the response object.
对于其他路线的请求,我在4分钟后收到net::ERR_EMPTY_RESPONSE
错误.
For requests to other routes I get the net::ERR_EMPTY_RESPONSE
error after 4 minutes.
如果我记录server.timeout
的值,则该值为120000
(2分钟).
If I log the value for server.timeout
, the value is 120000
(2 minutes).
我的问题
- 4分钟可能从哪里来?是因为可能有一个先前的OPTIONS请求吗?
- 服务器和服务器之间有什么区别?套接字超时以及如何为特定路由正确设置它们?
推荐答案
我已使用以下路由配置解决了该问题:
I've solved it using the following route configuration:
'use strict';
const ms = require('ms');
const express = require('express');
const router = express.Router();
router.route('/upload-files')
.post(
setConnectionTimeout('12h'),
require('./actions/upload-files').responseHandler
);
function setConnectionTimeout(time) {
var delay = typeof time === 'string'
? ms(time)
: Number(time || 5000);
return function (req, res, next) {
res.connection.setTimeout(delay);
next();
}
}
exports.router = router;
关键逻辑是以下中间件:
Where the key logic is the following middleware:
function (req, res, next) {
res.connection.setTimeout(delay);
next();
}
我希望此参考资料对其他人有用.
I hope this reference will come in handy for others.
这篇关于每个路由的节点Express特定超时值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!