我希望能够通过使用具有如下函数调用的 rest api 端点来搜索其名称属性与从我的 angular 应用程序输入的字符串相匹配的文档
exports.idea_search = function(req, res){
if(req.body.searchTerm){
Idea.find({name: req.body.searchTerm}).exec(function(err,docs){
res.json(docs)
});
}
else{
res.send(err);
console.log(err)
}
};
在端点上调用此控制器函数的角度函数如下所示(包括其他变量以供参考)
//api.service.ts
apiURL: string = 'http://localhost:3000/ideas'
constructor(private httpClient: HttpClient) { }
public searchIdeas(idea){
return this.httpClient.post(`${this.apiURL}/search`, idea);
}
//search.component.ts
searchIdeas(search){
this.apiService.searchIdeas(search).subscribe(data => this.idea = data);
};
当我从 api html 模板调用函数时,它可以工作,但是当我从 angular 应用程序调用它时,我收到这些错误
POST http://localhost:3000/ideas/search 500 (Internal Server Error)
ERROR
HttpErrorResponse {headers: HttpHeaders, status: 500, statusText: "Internal Server Error", url: "http://localhost:3000/ideas/search", ok: false, …}
error: "error"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://localhost:3000/ideas/search: 500 Internal Server Error"
name: "HttpErrorResponse"
ok: false
status: 500
statusText: "Internal Server Error"
url: "http://localhost:3000/ideas/search"
__proto__: HttpResponseBase
我尝试了一些不同的解决方案,例如使用 .then() 方法更改 api 函数以返回承诺,但我没有成功。在这一点上,我有点渴望解决方案
可能这就是为什么您期望在后端使用 req.body.searchTerm 的原因,而您从客户端发送的只是一个字符串,因此您的后端不知道“searchTerm”是什么。尝试像这样发送它:
public searchIdeas(idea){
return this.httpClient.post(`${this.apiURL}/search`, {searchTerm: idea});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句