[Hỏi] Router group " 'prefix => 'admin " ?
-
Dạ mọi người cho em hỏi ... Trong router express có dùng router group
Kiểu như các url trong admin thì ta có admin/....
Giờ admin lặp lại nhiều lần e muốn biết có cách nào để ta đặt nó thành 1 prefix ... Cũng như là cách middleware cho nó ạ .... Thanks mọi người ....
-
dùng app.use() đọc kỹ DOC của express đi
-
Ví dụ:
app.use('users', require('./controllers/user_controller'));
trong user_controller.js khai báo như sau:
router.get('/', getAllUser);=> api: user/getAllUser
-
@stmiizz Dạ e có tìm hiểu oy mà hok thấy nên mới post lên đây hỏi ấy ạ ... :((
-
@Tam-Phanminh
Dạ kiểu như vậy thì e biết
Nhưng e muốn khác ạ ..
Kiểu như e có các link
admin/category
admin/news
admin/users
giờ e muốn 1 cái prefix admin ý ạ... để khỏi phải làm kiểu .
app.use('/admin/user', user);
app.use('/admin/category', category);
Thanks anh ạ
-
@Nguyễn-Trọng-Hiếu Bạn có thể sử dụng
Router
từ phiên bản 4.
Document: https://expressjs.com/en/4x/api.html#routerVí dụ:
var express = require('express'); var app = express(); var router = express.Router(); // simple logger for this router's requests router.use(function(req, res, next) { // Middleware luôn chạy trên route /admin console.log('%s %s %s', req.method, req.url, req.path); next(); }); // this will only be invoked if the path starts with /category from the mount point router.use('/category', function(req, res, next) { res.send("Hello from category"); next(); }); router.use('/news', function(req, res, next) { res.send("Hello from news"); next(); }); router.use('/users', function(req, res, next) { res.send("Hello from users"); }); // always invoked router.use(function(req, res, next) { res.send('Hello World'); }); app.use('/admin', router); app.listen(3000, function () { console.log('Ready'); });
Việc còn lại là bạn sắp xếp lại cái router đó cho hợp lý. Có thể tổ chức ra một file riêng, hoặc thư mục riêng cho dễ quản lý.
-
@Vũ Dạ thanks anh ạ ...
Thế này theo e hiểu là mọi route đều nằm trong /admin
Giờ e muốn 1 route nào ngoài or 1 route /.. tương tự admin thì sao ạ ...
Em newbie hỏi hơi nhiều mong anh thông cảm :)))
-
@Nguyễn-Trọng-Hiếu Bạn làm tương tư như thế. Bạn sẽ cần tạo ra 2 router, giả sử là:
router1
,router2
. Sau đó mount vào express app như trên.app.use('/admin1', router1); app.use('/admin2', router2);
Chú ý là các router này có tính chất kế thừa, nên bạn có thể tạo nhiều cấp được. Tức là:
router1.use('/child', router2)
. Lúc này bạn sẽ có 2 route tương đương nhau là/admin2
và/admin1/child
. Hi vọng bạn hiểu
-
@Vũ Dạ thanks anh nhiều lắm ạ