express.js official migration guide is not sufficient yet.
- Check manually in your RequestHandler
- Be careful declaration order
// users.router.ts
import { Router } from "express";
const r = Router();
r.get("/", indexHandler);
-r.get("/:id(\\d)", showHandler);
-r.get("/new", newHandler);
+r.get("/new", newHandler); // `GET /new` must be before `GET /:id`
+r.get("/:id", showHandler); // ensure `:id` is number in `showHandler`
Though you have to care this even in express@4, req.body
might be undefined
where it was {}
in the previous version.
or you can add a middleware to set {}
when req.body === undefined
.
// my-middleware.ts
import { type RequestHandler } from "express";
const myMiddleware: RequestHandler = (req, _res, next) => {
- if (req.body.foo) {
+ if (typeof req.body === "object" && "foo" in req.body && req.body.foo) {
// do something
}
next();
};
// e.g.) GET /?foo=aaa
app.get("/", (req, res) => {
console.log(req.query);
// { foo: "aaa" }
req.query.foo = "bbb";
req.query.bar = "ccc";
console.log(req.query);
// { foo: "aaa" } // not affected
delete req.query.foo;
console.log(req.query);
// { foo: "aaa" } // not affected
req.query = { foo: "bbb" }
// TypeError
res.end();
});