节点 express.Router().route() 与 express.route()
node express.Router().route() vs express.route()
我应该用什么:
express.Router().route()
或
express.route()
?
这是真的吗 express.Router().route()
不知何故被弃用了?
对于当前版本的 Express,您应该使用 express.Router().route()
。请参阅快递 documentation 进行确认。 express.Router().route()
未折旧。
例如:
var router = express.Router();
router.param('user_id', function(req, res, next, id) {
// sample user, would actually fetch from DB, etc...
req.user = {
id: id,
name: 'TJ'
};
next();
});
router.route('/users/:user_id')
.all(function(req, res, next) {
// runs for all HTTP verbs first
// think of it as route specific middleware!
next();
})
.get(function(req, res, next) {
res.json(req.user);
})
.put(function(req, res, next) {
// just an example of maybe updating the user
req.user.name = req.params.name;
// save user ... etc
res.json(req.user);
})
.post(function(req, res, next) {
next(new Error('not implemented'));
})
.delete(function(req, res, next) {
next(new Error('not implemented'));
})
Router.route() 可用于可链接的路由。
意思是:你有一个 API 用于所有的方法,你可以把它写在 .route() 中。
var app = express.Router();
app.route('/test')
.get(function (req, res) {
//code
})
.post(function (req, res) {
//code
})
.put(function (req, res) {
//code
})
我应该用什么:
express.Router().route()
或
express.route()
?
这是真的吗 express.Router().route()
不知何故被弃用了?
对于当前版本的 Express,您应该使用 express.Router().route()
。请参阅快递 documentation 进行确认。 express.Router().route()
未折旧。
例如:
var router = express.Router();
router.param('user_id', function(req, res, next, id) {
// sample user, would actually fetch from DB, etc...
req.user = {
id: id,
name: 'TJ'
};
next();
});
router.route('/users/:user_id')
.all(function(req, res, next) {
// runs for all HTTP verbs first
// think of it as route specific middleware!
next();
})
.get(function(req, res, next) {
res.json(req.user);
})
.put(function(req, res, next) {
// just an example of maybe updating the user
req.user.name = req.params.name;
// save user ... etc
res.json(req.user);
})
.post(function(req, res, next) {
next(new Error('not implemented'));
})
.delete(function(req, res, next) {
next(new Error('not implemented'));
})
Router.route() 可用于可链接的路由。 意思是:你有一个 API 用于所有的方法,你可以把它写在 .route() 中。
var app = express.Router();
app.route('/test')
.get(function (req, res) {
//code
})
.post(function (req, res) {
//code
})
.put(function (req, res) {
//code
})