我正在尝试直接从请求访问路由,即使另一个子文件夹有效,另一个也不起作用。反复抛出404错误。 /api/getPostList
有效,但是/post/
或/post/:title
不起作用。
我已经重组了代码,试图将其从获取请求更改为发布请求,添加了/post/:title
来访问单个帖子,或者没有添加/
来访问主列表。
Server.js包含
app.use('/', Routes);
routes / index.js包含
const router = require('express').Router();
const posts = require('./posts');
const api = require('./api');
router.use('/post', posts);
router.use('/api', api);
module.exports = router;
routes / api / index.js包含
Api.get('/getPostList', (req, res) => {
PostModel.find(function (err, post) {
if (err) return console.log('error: ' + err);
return res.json({ postList: post});
});
console.log("Attempted to get post list on /getPost/ route: " + ++postRouteCnt);
});
Api.get('/getPost/:title', getPost);
module.exports = Api;
routes / post / index.js包含
const Posts = require('express').Router();
const post = require('./post');
const PostModel = require('../../../server/models.js');
let postRouteCnt = 0;
Posts.get('/', (req, res) => {
PostModel.find(function (err, post) {
if (err) return console.log('error: ' + err);
return res.json({ postList: post});
});
console.log("Attempted to get post list on /post/ route: " + ++postRouteCnt);
});
Posts.get('/:title', post);
module.exports = Posts;
当致电/post/
时,我应该收到JSON响应时收到404 Cannot GET /post/
。
编辑: 文件夹结构
Server/
routes/
api/
index.js
getPost.js (for individual post)
posts/
index.js
post.js (for individual post)
server.js
答案 0 :(得分:0)
尝试这样更改
Posts.get('/', (req, res) => {
PostModel.find(function (err, post) {
if (err) throw err;
res.send({ postList: post});
});
console.log("Attempted to get post list on /post/ route: " + ++postRouteCnt);
});
现在尝试使用该网址
/ post /
答案 1 :(得分:0)
根据您的结构文件夹,我尝试用简单的代码编写代码
App.js:
const express = require('express')
const app = express()
const port = 3000
const Routes = require('./routes/posts/index.js');
app.use('/', Routes);
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
.routes / posts / index.js:
const express = require('express');
const router = express.Router();
const postController = require('./post');
// GET /
router.get('/posts', postController.getPosts);
module.exports = router;
.routes / posts / post.js:
exports.getPosts = (req,res) => {
res.send('test');
}
尝试输入http://localhost:3000/posts及其工作
您可以在.routes / posts / post.js中编写任何逻辑: