node.js - Cant GET/ problem with express routes an localhost
问题描述
I watched a video by traversy media on youtube and after trying copying 1 for 1 his code i still didnt have any success with the problem. the code is suppose to route the main page('/') to the page(/routes/api/posts'), can anyone find the problem with my code? my index.js code:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
//Middleware
app.use(bodyParser.json());
app.use(cors());
const posts = require('./routes/api/posts');
app.use('/api/posts', posts);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('server started on port ' + port));
Posts.js page:
const express = require('express');
const mongodb = require('mongodb');
const router = express.Router();
//Get Posts
router.get('/', (req,res) => {
res.send('hello');
});
//Add Post
//Delete Post
module.exports = router;
Thanks and sorry for the bad english :(
解决方案
res.send('hello')
只能通过 访问GET /api/posts
。你应该使用:
const posts = require('./routes/api/posts');
app.use('', posts);
推荐阅读
- qt - 锁定 OpenMP
- python - 有没有办法只在 Counter() 输出中打印字典?
- javascript - 如何通过将html复制为另一个div中的文本来获取新行
- laravel - Laravel View to PDF:ol 的问题(有序列表)
- node.js - 获取打字稿错误(TS2430 和 TS2344):接口“响应”
' 错误地扩展接口 'ServerResponse' - ruby-on-rails - 没有路由匹配缺少必需的键:[:id]。破坏
- git - git index-pack 在 Ubuntu 20.04 中的 chromium 构建期间失败
- swiftui - SwiftUI:在工作表中更改亮/暗模式不会刷新工作表 UI
- botframework - 无法连接到远程机器人技能?
- xpath - Mule 3.9 - 无法使用 Xpath3 NODESET 的 foreach 获取 xml 值