【问题标题】:Which function should be used in angular to handle api post requests?Angular 中应该使用哪个函数来处理 api post 请求?
【发布时间】:2019-12-29 01:15:05
【问题描述】:

我希望能够通过使用看起来像这样的函数调用使用其余 api 端点来搜索其 name 属性与从我的 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 函数以返回一个承诺,但我没有成功。 在这一点上,我有点急于寻求解决方案

【问题讨论】:

  • 500 错误是 server 代码中的错误。您不会通过更改 client 代码来解决此问题。
  • @JBNizet 你看到 api 中的 idea_seach 函数有什么问题吗?

标签: node.js angular mongodb express mongoose


【解决方案1】:

可能这就是为什么您在后端期待 req.body.searchTerm,而您从客户端发送的只是一个字符串,所以您的后端不知道“searchTerm”是什么。尝试这样发送:

public searchIdeas(idea){
    return this.httpClient.post(`${this.apiURL}/search`, {searchTerm: idea});
  }

【讨论】:

  • 是的,谢谢,现在我在绑定到想法变量的文本输入中返回 [Object, Object]
  • 你能发布你的html吗?输入文本应该绑定到想法,而不是绑定到作为对象的 {searchTerm:idea}
猜你喜欢
  • 2020-02-01
  • 2021-04-02
  • 2015-06-28
  • 1970-01-01
  • 2012-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多