I've encountered some strange behaviour, by using middleware on my express backend.
I try to use the action middleware function before my invalidJsonDetection middleware function in index.js. If I destructure my action middleware function it is not working as expected, but if I assign the middleware function with middleware.general.action it is working as intended.
file 1: middleware.js
const middleware = {};
middleware.general = {
action(req, res, next) {
req.action = req.originalUrl; // simple task
next();
}
};
middleware.security = {
invalidJsonDetection(err, req, res, next) {
if (err instanceof SyntaxError && err.status === 400) {
// with destructuring: req.action === undefined
// without: req.action === req.originalUrl
res.json({ action: req.action, status: 'error' });
return;
}
next();
}
};
export default middleware;
file 2: index.js
import middleware from './middlewares/middleware.js';
const { action } = middleware.general;
const { invalidJsonDetection } = middleware.security;
const app = express();
// general middleware section
app.use(cors({ origin: 'http://localhost:8080', credentials: true }));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookieParser());
app.use(action); // not working
// app.use(middleware.general.action); // working
app.use(invalidJsonDetection); // working as expected
app.post('/', (req, res, next) => {
res.json({ status: 'test' });
return;
});
app.listen(8081, () => {
console.log(`Backend is listening on port 8081`);
initDatabase();
});
Maybe someone could help me with this.