Когда мы начинаем вводить маршруты в Express.JS, мы хотим разделить маршруты в другую папку.
Вот как должна выглядеть наша файловая структура
___________________
› Node_modueles
› Routes
— — — home.js
— — — users.js
app.js
package-lock.json package.json
_____________________
В каждом файле маршрута мы хотим импортировать экспресс и Router().
const express = require(‘express’); //this is like createing a mini express app, or a pluggin const router = express.Router(); //syntax include, remeber that all of these are functions. router.use; //important to keep in mind that this does not to an exact route match //get, post, put, delete will all do and exact route match router.get; router.post; router.put; //not one hundered on this but I’m sure that destroy is something like this router.delete; module.exports = router;
Чтобы использовать наши новые файлы маршрутов, мы должны импортировать их и вызывать с помощью экспресс-метода use().
//IN app.js const express = require('express'); const app = express(); const myRoute = require('./routes/<file name>'); const anotherRoute = require('./routes/<another file name>') const bodyParser = require('body-parser') app.use(bodyParser.urlencoded({extended: false})) app.use(myRoute) app.use(anotherRoute) app.listen(3000) //easy peasy
Давайте сделаем ошибку 404.
//js executes from top to bottom ... app.use((req, res, next)=>{ res.status(404).send('<h1>Page not found</h1>'); }) //we can always chain res whit .status(code number) or .setHeaders(header) app.listen(3000)
фильтрация путей
Еще одна интересная особенность express.js — мы можем фильтровать пути.
//all we have to do is add and argument to app.use('/route', routeName) ... app.use('/admin', adminRoutes) app.listen(3000) // keep in mind this only works if your have to routes with the same path but not the same method like so router.get('/add-product', (req, res, next) => { res.send('<form action="/admin/add-product" method="POST"><input type="text" name="title"><button>Add Product</button></form>') }); //notice that the acton still uses /admin that is becuse we will still be going to /admin/add-product router.post('/add-product', (req, res, next) => { console.log((req.body.title)) res.redirect('/') }) //again we redirect to /admin/add-product