處理我必須接受上傳文件的路徑:不確定錯誤快遞
在app.js
.
.
.
var upload = require('./routes/upload');
.
.
.
app.use('/upload', upload);
.
.
.
/* Need to start the application with NODE_ENV=production */
app.use(function (err, req, res, next){
if (res.headersSent) {
return next(err)
}
res.status(500)
res.render('An error occured while trying to serve your request. Please send us an email if the error recurs.')
});
app.listen(3000);
而且在路線/ upload.js,我接受文件前檢查文件類型和在數據庫中創建一個條目。我還檢查文件寫入錯誤時,我試圖通過調用next(ERR)內handleFileUpload傳遞到app.js錯誤處理程序,如下圖所示:
var express = require('express');
var router = express.Router();
var path = require('path');
var mysql = require('mysql');
var multer = require('multer');
var fs = require('fs');
var db = require('../database');
var MAGIC_NUMBERS = {
jpg: 'ffd8ffe0',
jpg1: 'ffd8ffe1',
png: '89504e47'
}
/* Adapted from https://evdokimovm.github.io/javascript/nodejs/expressjs/multer/2016/11/03/Upload-files-to-server-using-NodeJS-and-Multer-package-filter-upload-files-by-extension.html */
function checkMagicNumbers(magic) {
if (magic == MAGIC_NUMBERS.jpg || magic == MAGIC_NUMBERS.jpg1 || magic == MAGIC_NUMBERS.png)
return true;
}
function handleFileUpload(req, res, next){
var upload = multer({
storage: multer.memoryStorage(),
}).single('fileUpload');
upload(req, res, function(err) {
var buffer = req.file.buffer;
var magic = buffer.toString('hex', 0, 4);
var filename = req.file.fieldname + '-' + req.file.originalname.replace(/\s+/g,'') + '-' + Date.now() + path.extname(req.file.originalname);
if (checkMagicNumbers(magic)) {
fs.writeFile('/uploads/' + filename, buffer, 'binary', function(err) {
if (err){
console.log(err);
return next(err);
}
else{
req.savedfilename = filename;
next();
}
})
} else {
res.end('File is not of the following accepted types: jpeg, jpg, png.');
}
});
}
function handleDatabaseInsert(req, res, next)
{
db.insertRecord(req.body.name, req.body.email, req.body.message,
req.body.country, req.savedfilename, function(err, results){
if(err)
next(err);
});
res.end("Thank you for your participation! Please look forward to our email with updates.");
}
/* POST to Upload */
router.post('/', handleFileUpload, handleDatabaseInsert)
module.exports = router;
的問題是,當我試圖趕上嘗試寫入文件並將其傳遞到app.js中的錯誤處理程序時,可能會發生錯誤,該錯誤處理程序在handleFileUpload內部,將調用下一個中間件handleDatabaseInsert,而不是使應用程序在app.js結束前使用的錯誤處理程序我讓應用程序聽。
這是預期的行爲?我認爲具有4個形式參數的函數將被調用來處理錯誤?
注:我故意用一個不存在的文件路徑模擬寫入錯誤,在這種情況下/上載/而不是./uploads/
謝謝!
我下面這個頁面描述的錯誤處理機制:[錯誤在快速處理(HTTP:/ /expressjs.com/en/guide/error-handling.html)。因爲它說調用next()以外的任何參數都會將該請求視爲錯誤,並調用錯誤處理路由。我在app.js中有一個全局錯誤處理路線,並希望路線能夠處理它。但我想我現在要通過使用res.end()來解決這個問題。 – mod0