0

Есть проект с такой структурой:

        |_catalog(dir) _ index.js
        |              _ method1.js
        |              _ method2.js
        |
        |_app.js 
  

Мне нужно, что бы при запросе по site.com/catalog/
модуль app.js передавал обработку модулю index.js, а index.js обрабатывал urlы site.com/catalog/method1 site.com/catalog/method2 ну и вызывал соответствующие модули.

Пробовал вот так:

app.js

const mainCatalog = require ("./catalog/index");

app.get('/catalog*', function (req, res) {
    mainCatalog(); 
});

index.js

const method1 = require ("./catalog/method1");

function foo () {
    app.get('/catalog/method1', function (req, res) {
        method1();
    });
}

module.exports = foo;

Но ничего не выходит.

2
  • 1
    Делается это через express.Router (в самом низу)
    – MoloF
    22 июл 2020 в 8:38
  • У вас слеш пропущен /catalog/* 22 июл 2020 в 8:52

1 ответ 1

2

Возможное, вот так:
index.js

const express = require('express');
const method1 = require ("./catalog/method1");

const router = express.Router(); // Создаем роутер

router.get('/method1', function(req, res) { // Самая обычная обработка запроса
    method1();
});

module.exports = router;

app.js

// Вместо этого комментария вероятное стоит require('express')
const mainCatalog = require ("./catalog/index");

// Тут где-то инициализация app

app.use('/catalog', mainCatalog); // Теперь по запросу "/catalog/mathod1" вызывается method1()
2
  • Это не работает. делаю запрос 127.0.0.1:3000//catalog/method1 бесконечно грузится, но и не отбивает с "Cannot GET". Скорее всего, дело в этой строчке app.use('/catalog', mainCatalog); она не передаёт дальше управление. 22 июл 2020 в 10:18
  • а не, всё ок, сам затупил. 22 июл 2020 в 11:05

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.