无法在Express NodeJS中配置路由器

时间:2018-05-20 18:04:23

标签: node.js express express-router

我有下一个服务器文件:

'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 - {{1 }} ...

我做错了什么?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

// ./routes/chat.js

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

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

module.exports = router;

你可以用这个