我张贴了大量的文件,可能需要几分钟才能上传。我使用多部分表单来发布文件,然后等待来自发布的响应,但这可能需要几分钟的时间。
如何让Node/Express等待此响应?到目前为止,似乎请求“超时”了,Node或浏览器正在重新发布文件,因为它花费了太长时间。我之所以能看到这一点,是因为我的中间件函数被多次调用,以处理耗时太长的请求。
有没有库可以让Node不超时?我是否应该尝试以不同的方式发布这些文件?谢谢
var mid = function(req,res,next) {
console.log('Called');
next();
};
app.post('/api/GROBID', mid, authenticate, PDFupload.return_GROBID, PDFupload.post_doc, function(req, res) {
if (res.locals.body == 400) res.send(400);
/*if (process.env.TEST_ENV == 'unit-testing') {
res.send(res.locals.body);
}*/
res.render('uploads', {files : res.locals.body});
});编辑:这个中间件(用作示例)被调用了两次。这意味着该路由将被发布两次。如何确保这种情况不会发生?
发布于 2018-01-20 07:52:00
有没有库可以让Node不超时?
Express位于Node.js' built-in HTTP server之上。默认情况下,超时为2分钟。您可以修改默认超时时间,如下所示:
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
app.get('/', function(req, res) {
res.send('<html><head></head><body><h1>Hello world!</h1></body></html>');
});
var server = app.listen(port);
server.timeout = 1000 * 60 * 10; // 10 minutes我是否应该尝试以不同的方式发布这些文件?
是的,您可以使用Multer,这是一个用于处理多部分/表单数据的node.js中间件,它主要用于上传文件。
有了Multer,你再也不用担心超时了。事件上传时间超过超时时间,默认情况下为2分钟,Express不会超时。
以下是示例代码:
app.js
var express = require('express');
var app = express();
var path = require('path');
var multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/your/path/to/store/uploaded/files/')
},
filename: function (req, file, cb) {
// Keep original file names
cb(null, file.originalname)
}
})
var upload = multer({ storage: storage })
// files is the name of the input html element
// 12 is the maximum number of files to upload
app.post('/upload', upload.array('files', 12), async (req, res) => {
res.send('File uploaded!');
})
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(3000);index.html
<html>
<body>
<form ref='uploadForm' id='uploadForm'
action='http://localhost:3000/upload'
method='post'
encType="multipart/form-data">
<input type='file' name='files' multiple/>
<input type='submit' value='Upload!' />
</form>
</body>
</html>现在尝试启动web服务器:
node app.js然后打开浏览器并转到http://localhost:3000
您现在可以上传许多大文件,稍后可以在文件夹/your/path/to/store/ upload / files /中找到这些文件
https://stackoverflow.com/questions/48346580
复制相似问题