簡體   English   中英

如何使Node.js等待來自大型請求的響應

[英]How to make Node.js wait for response from a large request

我發布了大量可能需要幾分鍾才能上傳的文件。 我使用多部分表單發布文件,然后等待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的內置HTTP服務器之上。 默認情況下,超時為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 /中找到/ store / uploaded / files /

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM