应该在 angular 中使用哪个函数来处理 api post 请求?

廉洁

我希望能够通过使用具有如下函数调用的 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如果可以在客户端处理对 API 的错误请求,是否应该在那里处理?

我应该在GET和POST请求中转义字符吗?

我应该在 Android 上 Flurry 的新 GDPR API 中使用哪个 ID?

我应该在Google翻译api请求正文中输入什么参数?

为什么应该在componentDidMount中而不是在ReactJS中使用getInitialState进行异步请求?

ReactJS 如何理解应该在哪个端口发出请求

我应该在香草Django中处理Ajax请求还是在Django其余部分处理?

是否应该在http请求goroutine之外处理所有独立任务?

我应该在 Angular 应用程序中有 API 模型和 UI 模型吗

我应该在Post方法中输入哪个IP地址?

我应该在Angular指令中使用单个对象还是单个值作为属性?

什么时候应该在Angular 2中使用var或let?

我应该在Angular 2中使用什么UI前端框架

我应该在Angular的可重用组件中使用EventEmitter还是共享服务?

为什么我应该在 Angular 订阅中使用带有管道的选择?

Angular 2 是否应该在组件 ts 中声明仅在模板中使用的变量?

我应该在单个wordpress模板中使用$ post = Timber :: query_post()还是$ post = new TimberPost()?

什么时候应该在Web API中使用HttpRequestMessage作为参数

我应该在REST API中使用PATCH还是PUT?

什么时候应该在spark编程中使用groupByKey API?

我应该在Web API中使用DTO接口吗?

我应该在REST Api中使用哪些头盔模块

我应该在restful api中使用不同的状态代码,而不是200吗?

我应该在哪个模块中声明 Angular 指令?

从Angular到Spring Rest API的POST请求

是否应该在REST API PUT请求中传递资源及其相关资源的所有字段?

我应该在Angular的类中将方法编写为箭头函数吗

为什么我们应该在Angular中的map()上使用subscribe()?

为什么我应该在简单的对象配置上使用Angular的依赖注入?