Answer the question
In order to leave comments, you need to log in
How to compose regex in express route?
Colleagues good day, I am writing an application on nodejs and the question arose of organizing a universal router so as not to write routes for each url. but there was a problem and I can not understand why:
here is the entry point, the main file:
const path = require('path');
const http = require('http');
const express = require('express');
const minify = require('express-minify-html');
const favicon = require('express-favicon');
const staticAsset = require('static-asset');
const compression = require('compression');
const config = require('./config.json');
const router = require('./controllers/router');
const app = express();
app.use(compression());
app.use(minify({
override: true,
exception_url: false,
htmlMinifier: {
removeComments: true,
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeEmptyAttributes: true,
minifyJS: true,
minifyCSS: true
}
}));
app.use(favicon(path.join(__dirname, 'public/images/favicon.png')));
app.set('views', path.join(__dirname, 'templates'));
app.set('view engine', 'ejs');
app.use(staticAsset(__dirname + '/public'));
app.use(express.static(__dirname + '/public'));
app.use(router);
app.use((req, res, next) => {
next(404);
});
app.use((err, req, res, next) => {
res.status(err.status || 404);
console.log(err + ' : ' + req.url);
res.render('index.ejs', {
template: './pages/404',
description: '404 не найдено',
keywords: '404 не найдено'
});
});
const server = http.createServer(app);
server.listen(config.port, () => {
console.log('server is ready');
});
// router
'use strict';
const express = require('express');
const router = express.Router();
const map = require('./map');
router.get(/\/([a-z\-]*)/gi, map.get);
module.exports = router;
Answer the question
In order to leave comments, you need to log in
/^(\/news\/)[0-9]+/
for /news/any_number_or_number
for /news/sport/any_number_or_number
Test on the site click
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question