【发布时间】:2019-08-27 11:14:30
【问题描述】:
在我的书评网站的搜索选项中,用户可以通过author 名称或genre 搜索书籍。对于那些我在下面的search.service.ts 中有单独的功能。后端也有单独的控制器。但是在搜索时,它只执行第一个控制器,即使路由指向它,它也不执行第二个控制器。
这里是search.service.ts函数,
getPostsByAuthor(author: string) {
this.http.get<{message: string, posts: any, maxPosts: number }>(BACKEND_URL + 'api/search/' + author)
.pipe(map((postData) => {
console.log(postData);
return { posts: postData.posts.map((post) => {
return {
title: post.title,
content: post.content,
author: post.author,
genre: post.genre,
id: post._id,
imagePath: post.imagePath,
creator: post.creator
};
}),
maxPosts: postData.maxPosts};
}))
.subscribe(transformedPostsData => {
this.posts = transformedPostsData.posts;
return this.posts;
});
}
getPostsByGenre(genre: string) {
this.http.get<{message: string, posts: any, maxPosts: number }>(BACKEND_URL + 'api/search/' + genre)
.pipe(map((postData) => {
console.log('Genre_');
console.log(postData);
return { posts: postData.posts.map((post) => {
return {
title: post.title,
content: post.content,
author: post.author,
genre: post.genre,
id: post._id,
imagePath: post.imagePath,
creator: post.creator
};
}),
maxPosts: postData.maxPosts};
}))
.subscribe(transformedPostsData => {
this.posts = transformedPostsData.posts;
return this.posts;
});
}
app.js中的路由,
app.use('/api/search', searchRoutes);
路由文件夹中的search.js,
const express = require('express');
const router = express.Router();
const SearchController = require('../controllers/search');
router.get("/:author", SearchController.getPostsByAuthor);
router.get("/:Genre", SearchController.getPostsByGenre);
module.exports = router;
这是连续给出的控制器,
const Post = require('../models/post');
const User = require('../models/user');
exports.getPostsByAuthor = (req, res, next) => {
let maxPosts = 10;
Post.find({ author: req.params.author }).then(posts => {
if(posts) {
res.status(200).json({
posts,
message: "Post was successful",
max: maxPosts
});
} else {
res.status(500).alert('Not Found, double check the spelling').json({
message: "Failed to get User Post"
});
}
});
}
exports.getPostsByGenre = (req, res, next) => {
let maxPosts = 10;
Post.find({ genre: req.params.genre }).then(posts => {
if(posts) {
res.status(200).json({
posts,
message: "Post weirdo successful",
max: maxPosts
});
} else {
res.status(500).json({
message: "Failed to get User Post"
});
}
});
}
它总是运行第一个表示getPostsByAuthor,它从不运行第二个。
我已经通过更改顺序进行了检查,当我确实将 getPostsByGenre 放在第一个位置时,它运行了,而 getPostsByAuthor 没有运行,因为它被放置在第二个位置。
控制器按顺序排在第一位,返回数据完美,表示路由到达controller文件。
我不明白是什么问题。在 SO 中没有找到类似的问题。
我仍然是使用 MEAN 堆栈进行开发的新手,最少的线索将意味着很大的帮助。谢谢你。
【问题讨论】:
-
在
exports.getPostsByGenre函数中,你应该使用User.find而不是Post.find吗? -
感谢您的回复。我刚试过,它没有用。 :-/
-
如果我理解正确,您希望同时执行
getPostsByAuthor和getPostsByGenre路由? -
不,用户要么按作者搜索,要么按流派搜索。两者都有单独的按钮,带有单独的事件触发单独的功能,但不是同时。
标签: node.js angular typescript express mean-stack