代码之家  ›  专栏  ›  技术社区  ›  Max Wolfen

无法在Express Nodejs中配置路由器

  •  0
  • Max Wolfen  · 技术社区  · 6 年前

    我有下一个服务器文件:

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

    第一个 索引.js 标准端口正常加载 localhost:8989/ 但是当我要走第二条路的时候 localhost:8989/chat -我总是收到 error - Cannot GET /chat

    我做错什么了?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Ritwick Dey    6 年前

    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!');
        });
    
        2
  •  0
  •   Mário Lucas    6 年前
    // ./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;
    

    你可以用这个

    推荐文章