You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular调用NodeJS API搜索接口报404错误求助

问题排查与解决

核心原因:请求方式与参数传递不匹配

你在Postman中使用的是GET请求,通过URL查询参数?first_name=kobinath传递数据,但Angular代码里用的是POST请求,把参数放在请求体里发送。后端的/user/findOne接口应该只配置了GET请求的处理逻辑,所以POST请求会返回404。

解决方案1:改为GET请求并传递查询参数

修改employee.component.ts的search方法,使用GET请求并通过查询参数传递姓名:

// 先导入HttpParams
import { HttpParams } from '@angular/common/http';

// ...

search() {
  // 构建查询参数
  const params = new HttpParams().set('first_name', this.first_name);
  
  this.http.get("http://localhost:9001/user/findOne", { params }).subscribe((resultData: any) => {
    console.log(resultData);
  });
}

解决方案2:修复表单默认提交行为

你的按钮是type="submit",点击时会触发表单的默认提交行为,可能导致页面刷新或干扰AJAX请求。可以做以下调整:

  • 把按钮类型改为button:
<button type="button" class="btn btn-primary mt-4" (click)="search()" >Search</button>
  • 或者在search方法中阻止默认事件:
search(event: Event) {
  event.preventDefault(); // 阻止表单默认提交
  const params = new HttpParams().set('first_name', this.first_name);
  
  this.http.get("http://localhost:9001/user/findOne", { params }).subscribe((resultData: any) => {
    console.log(resultData);
  });
}

对应的HTML修改为:

<button type="submit" class="btn btn-primary mt-4" (click)="search($event)" >Search</button>

额外检查点

如果后端确实支持POST请求,需要确认:

  1. 后端的POST接口路径是否为/user/findOne
  2. 后端是否配置了解析JSON请求体的中间件(比如Express的express.json())

内容的提问来源于stack exchange,提问作者nanda kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 17:10:36