[英]Can't get data for req.body with mean stack
嘿,使用req.body时似乎看不到任何结果。 尝试将数据从mongodbdatabase转换为json格式,这是我的代码:
我的服务器文件:
app.get('/api/category/posts', (req, res) => {
Post.find({ categoryId: req.body._id }, function(err, posts) {
res.json(posts);
});
});
服务文件:
getPosts(_id): Observable<Post[]>{
return this.http.get<Post[]>(this.apiUrl +"/category/posts");
}
component.ts
this.appService.getPosts(_id)
.subscribe(data =>this.posts=data);
您的api方法是get方法,并且您需要_id在req.body中。 这是错误的。
您需要更改获取请求以同时发布在服务器文件和服务文件中的请求,或者尝试在req.params或req.query中传递_id:-
如果您通过_id作为req.query:-
您的服务器代码将类似于:
app.get('/api/category/posts', (req, res) => {
Post.find({ categoryId: req.query._id }, function(err, posts) {
res.json(posts);
});
});
服务档案
getPosts(_id): Observable<Post[]>{
return this.http.get<Post[]>(this.apiUrl +"/category/posts"+'?_id='+_id);
}
component.ts将相同。
如果您想使用post方法检查req.body,则您的代码将更改为:
您的服务器代码将类似于:
app.post('/api/category/posts', (req, res) => {
Post.find({ categoryId: req.body._id }, function(err, posts) {
res.json(posts);
}); });
服务档案
getPosts(_id): Observable<Post[]>{
return this.http.post<Post[]>(this.apiUrl +"/category/posts",{_id:_id});
}
component.ts将相同。
按照REST架构获取资源,您应该在get request参数中传递_id。 您还可以使用简单的正则表达式模式来验证id
参数,以确保传递的id
是数字
快速路线
app.get('/api/category/posts/:id(\\d+)', (req, res) => {
Post.find({ categoryId: req.params.id }, function(err, posts) {
res.json(posts);
});
});
服务档案
getPosts(_id): Observable<Post[]>{
return this.http.get<Post[]>(`${this.apiUrl}/category/posts/${_id}`);
}
组件文件
this.appService.getPosts(_id)
.subscribe(data =>this.posts=data);
作为一种好习惯,您还应该跟踪您的订阅,并在完成操作或销毁组件时取消订阅,或者在first
订阅后使用第first
运算符取消订阅。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.