Search code examples
node.jsexpressexpress-router

Cannot configure Router in Express NodeJS


I have the next server file:

'use strict'

const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);

const index = require('./routes/index');
const chat = require('./routes/chat');

app.use('/', index);
app.use('/chat', chat);

const port = process.env.API_PORT || 8989;
server.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

and the next two routes index.js and chat.js in ./routes dir:

// ./routes/index.js

const express = require('express');
const router = express.Router();

router.route('/')
    .get((req, res) => {
        res.json('Hello on the Homepage!');
    });

module.exports = router;



// ./routes/chat.js

const express = require('express');
const router = express.Router();

router.route('/chat')
    .get((req, res) => {
        res.json('Hello on the Chatpage!');
    });

module.exports = router;

The first one index.js loads normaly by standart port localhost:8989/, but when I what to get the second route by localhost:8989/chat - I always receive error - Cannot GET /chat...

What is I'm doing wrong?


Solution

  • In server.js

    const index = require('./routes/index');
    const chat = require('./routes/chat');
    
    
    app.use('/chat', chat); // when path is :/chat/bla/foo
    app.use('/', index); 
    

    In ./routes/index.js

    router.route('/')
        .get((req, res) => {
            res.json('Hello on the Homepage!');
        });
    

    In ./routes/chat.js

    // It is already in `:/chat`. There we need to map rest part of URL.
    router.route('/')  
        .get((req, res) => {
            res.json('Hello on the Chatpage!');
        });