在重定向之前立即调用flash()时,出现重复错误。
代码是对员工显示的简单处理:
const express = require('express')
const flash = require('express-flash-notification');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const app = express()
app.use(cookieParser())
app.use(session({
secret: 'secretapp',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}))
app.use(flash(app))
app.get('/employee/:id*?', (req, res) => {
console.log('got a request to display');
if (req.params.id) {
console.log('got a request to display user ' + req.params.id);
if (req.params.id==1234) {
return res.render('employee.hbs', {
first: "Holy",
last: "Mitchell"
});
} else {
// *********** I get an error only when flashing:
req.flash('warning', 'Employee does not exist')
// *********** No error when commenting out req.flash()
return res.redirect('/employee/');
}
} else {
return res.render('employee_lookup.hbs');
}
});
错误看起来像这样(我收到数十个错误):
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (.../addressbook/node_modules/express/lib/response.js:767:10)
at ServerResponse.location (.../addressbook/node_modules/express/lib/response.js:884:15)
at ServerResponse.redirect (.../addressbook/node_modules/express/lib/response.js:922:18)
at app.get (.../addressbook/index.js:37:24)
at Layer.handle [as handle_request] (.../addressbook/node_modules/express/lib/router/layer.js:95:5)
at next (.../addressbook/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (.../addressbook/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (.../addressbook/node_modules/express/lib/router/layer.js:95:5)
at .../addressbook/node_modules/express/lib/router/index.js:281:22
再次强调一下,无需调用flash()即可按预期工作。