首页 > 解决方案 > 无法在 Express NodeJS 中配置路由器

问题描述

我有下一个服务器文件:

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

以及接下来的两条路线和index.js目录:chat.js./routes

// ./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;

第一个index.js通过标准端口正常加载localhost:8989/,但是当我得到第二个路由时-我localhost:8989/chat总是收到error-...Cannot GET /chat

我在做什么错?

标签: node.jsexpressexpress-router

解决方案


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

./routes/index.js

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

./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!');
    });

推荐阅读