M
M
Michael2019-03-13 16:50:36
JavaScript
Michael, 2019-03-13 16:50:36

Why doesn't routing work in Express.js through Router?

I can't get the application to work through the Router object in Express.
The structure of the application is as follows (what is relevant to the problem):
index.js
fn.js
/routes/getSettings.js
Code in index.js

const express = require('express');
const getSettingsRouter = require('./routes/getSettings');
const app = express();

app.use('/getSettings', getSettingsRouter);

getSettings.js code
const express = require('express');
const router = express.Router();
const fn = require('../fn.js');

router.get('/getSettings', async (req, res) => {
    let response = await fn.getSettings();
    res.type('json');
    res.send(response);
});

module.exports = router;

As a result, 404 is issued along the /getSettings path. If you put the routing code in index.js (replacing router.get with app.get accordingly), everything works correctly. I suspect that the problem is either in the paths or in the export-import, but I can’t get it to work as expected on my own.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
marginBottom, 2019-03-13
@marginBottom

Fix to
app.use('/', getSettingsRouter);

H
hzzzzl, 2019-03-13
@hzzzzl

Here you made a route /getSettings/getSettings

M
monochromer, 2019-03-13
@monochromer

It seems to me that it is more correct to replace this in the /routes/getSettings.js file
on this
router.get('/', async (req, res) => { /*...*/ })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question