javascript之如何让 Node.js 等待来自大请求的响应

cloudgamer 阅读:15 2024-12-31 21:38:35 评论:0

我要发布大量可能需要几分钟才能上传的文件。我使用多部分表单发布文件,然后等待 POST 的响应,但这可能需要几分钟时间。

如何让 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}); 
}); 

编辑:这个中间件(用作示例)被调用了两次。这意味着该路线被发布到两次。我如何确保不会发生这种情况?

请您参考如下方法:

有没有让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 ,一个用于处理 multipart/form-data 的 node.js 中间件,主要用于上传文件。

有了 Multer,您再也不用担心超时了。如果上传时间超过超时时间,默认为 2 分钟,Express 不会超时。

示例代码如下:

应用程序.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> 

现在尝试启动网络服务器:

node app.js 

然后打开浏览器并转到http://localhost:3000

您现在可以上传一些大文件,稍后您可以在文件夹/your/path/to/store/uploaded/files/中找到这些文件


标签:JavaScript
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号