我有接受文件上传的路线:
在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);
在routes / upload.js中,我在接受文件并在数据库中创建条目之前检查文件类型。我还检查文件写入过程中的错误,我尝试通过在handleFileUpload中调用next(err)来传递给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;
问题是当我试图捕获在尝试编写文件并将其从handleFileUpload内部传递到app.js中的错误处理程序时可能发生的错误时,调用下一个中间件handleDatabaseInsert而不是错误处理程序在我让app听之前,我在app.js结束时使用了app。
这是预期的行为吗?我认为将调用带有4个形式参数的函数来处理错误?
注意:我故意通过使用不存在的文件路径来模拟写入错误,在这种情况下是/ uploads /而不是./uploads /
谢谢!
答案 0 :(得分:1)
如果我理解正确,您希望在出现某种错误时停止请求。为此,您只需停止致电next()
调用next()
运行下一个创建的中间件函数如果您不希望它运行下一个中间件项,请不要调用next()
。
您可能希望使用res.send(500)
代替next()
或类似内容。
如果你想创建一个错误处理程序,你也可以这样做:
http://expressjs.com/en/guide/using-middleware.html#middleware.error-handling