R
R
Roman Andreevich2019-03-05 07:36:06
JavaScript
Roman Andreevich, 2019-03-05 07:36:06

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');

});

I think everyone understands what is happening there. There is also a router
// 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;

So, the idea is that you need to parse the url, the url can look like this:
/
/news
/news/
/news/sport
/news/sport/
/news/sport/12234
/news/sport/12234/
Here I think the same clear. But now a problem has arisen, the desired page opens every other time, i.e. either a 404 is issued or the page you need, please help, tell me, maybe there is an error somewhere?
Thank you in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alisher Aidarkhan, 2019-03-12
@alikenski

/^(\/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 question

Ask a Question

731 491 924 answers to any question