node.js - 无法在 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
我在做什么错?
解决方案
在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!');
});
推荐阅读
- css - flexbox 下拉菜单,菜单故意重叠子菜单链接
- regex - 正则表达式 - 如何从备份到第二个斜杠中选择一组字符?
- java-11 - Java 11 - java/beans/PropertyChangeListener
- python-3.x - 通过 stem 的多个 Tor 实例
- r - emo::ji 不会在针织文档中呈现
- reactjs - React-Native 背景图像 - 如何水平重复和 100% 高度
- android-studio - 构建ionic 4应用程序时android studio中的错误
- node.js - 如何在新的 7.3.0 版本的 Elasticsearch 中使用我的 6.4.1 版本的 Elasticsearch 数据?
- recaptcha - 为什么子域不能与 reCaptcha 一起使用?
- java - 如何使用 GraalVM 在现有 grails 或 spring 应用程序中运行 javascript?