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

Angular+NodeJS集成API返回404错误,请求排查原因

问题

我一直在尝试创建服务器并与前端集成。我使用NodeJS搭建了后端服务,开发了若干API接口,可通过注册表单创建患者信息。但将其与Angular前端集成时,一直出现相同的错误:前端服务中配置的Base URL返回404页面未找到。

以下是后端相关路由代码:

后端主文件 server.js

import express,{json,urlencoded} from 'express';
import cors from "cors";
import db from './App/Models/index.js';
import {patientrouter} from './App/Routes/patient.routes.js'
import { caretakerrouter } from "./App/Routes/caretaker.routes.js";
import { doctorrouter } from './App/Routes/doctor.routes.js';

const app = express()
var corurl = {origin: "http://localhost:8080"}

app.use(cors(corurl))
app.use(json())
app.use(urlencoded({extended: true }))

/* REQUESTS and ROUTES */

app.get("/", (req, res) => {
    res.json({Message:"Hello, Welcome to Wearable."})
})

app.use('/add', patientrouter);
// app.use('/Doctor', doctorrouter);
// app.use('/CareTaker', caretakerrouter);

const port = process.env.PORT || 8080;
app.listen(port, () => {
    console.log(`Server is running on port ${port}.`);
});

路由处理文件 patient.route.js

import {Patientcreate, PatientFindAll, PatientFindOne, PatientUpdate} from '../Controllers/patient.controller.js'
import {Router as routerman} from 'express'

const patientrouter = routerman()
patientrouter.post("/",Patientcreate)
patientrouter.get("/",PatientFindAll)
patientrouter.get("/Find/:Name",PatientFindOne)
patientrouter.put("/Update/:ID",PatientUpdate)

export {patientrouter}

前端相关代码

路由模块 routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AddPatientComponent } from "./components/add-patient/add-patient.component";

const routes: Routes = [
  {path: '', redirectTo: 'patient', pathMatch: 'full'},
  {path: 'add', component: AddPatientComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

患者服务 patient.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { Patient } from "../models/patient.model";

const baseUrl = 'http://localhost:8080/add'

@Injectable({
  providedIn: 'root'
})
export class PatientService {

  constructor(private http: HttpClient) { }

  create(data: any): Observable<any> {
    return this.http.post(baseUrl, data);
  }
}

添加患者组件 addpatient.component.ts

import { Component, OnInit } from '@angular/core';
import { Patient } from "src/app/models/patient.model";
import { PatientService } from "src/app/service/patient.service";

@Component({
  selector: 'app-add-patient',
  templateUrl: './add-patient.component.html',
  styleUrls: ['./add-patient.component.css']
})
export class AddPatientComponent implements OnInit{

  patient: Patient = {
    Name: '',
    Mobile_Number: NaN,
    Username: '',
    Password: '',
    Gender: ''
  };
  submitted = false;

  ngOnInit(): void {
    console.log(this.submitted)
  }
  constructor(private patientservice: PatientService){}

  savepatient(): void {
    const data = {
      Name: this.patient.Name,
      Username: this.patient.Username,
      Password:this.patient.Password,
      Mobile_Number:this.patient.Mobile_Number,
      Gender:this.patient.Gender

    };

    console.log(data)

    this.patientservice.create(data)
      .subscribe({
        next: (res) => {
          console.log(res);
          this.submitted = true;
        },
        error: (e) => console.error(e)
      });
  }

  newpatient(): void {
    this.submitted = false;
    this.patient = {
      Name: '',
      Username: '',
      Password: '',
      Mobile_Number: NaN,
      Gender: ''
    };
  }

}

我已通过Postman测试后端服务,一切正常,但在Angular网页中调用时错误重现。我不确定问题出在哪里,原本以为调用服务后会执行函数并通过服务器添加数据。请告知前后端集成的方法,我是否遗漏了关键步骤?错误原因是什么?代码基于bezkoder网站示例,NodeJS、Angular、MongoDB均为最新版本。


错误分析与解决步骤

核心错误原因

Angular前端默认启动端口为4200,但后端CORS配置仅允许http://localhost:8080的请求,前端实际运行端口不在允许范围内,导致请求被浏览器跨域拦截,最终表现为404错误(实际是跨域拦截后的伪装错误)。同时需确认后端确实运行在8080端口,避免端口冲突。

具体修复步骤

  1. 修正后端CORS配置
    修改server.js中的CORS配置,允许前端所在的4200端口:

    var corurl = {origin: "http://localhost:4200"}
    

    若需允许多个端口,可改为数组形式:

    var corurl = {origin: ["http://localhost:4200", "http://localhost:8080"]}
    
  2. 确认前后端端口一致性

    • 后端当前配置端口为8080,启动时需确保该端口未被其他服务占用。
    • 若修改过Angular启动端口,需同步更新CORS配置中的origin值。
  3. 验证前端HttpClient模块导入
    确保Angular的AppModule中已导入HttpClientModule,否则无法发起HTTP请求:

    import { HttpClientModule } from '@angular/common/http';
    
    @NgModule({
      imports: [
        // 其他模块
        HttpClientModule
      ],
      // 其他配置
    })
    export class AppModule { }
    
  4. 确认API路径与请求方法匹配
    后端/add路由挂载patientrouter后,POST请求路径为http://localhost:8080/add,前端baseUrl配置正确;需同时确认Patientcreate控制器函数逻辑正常,能处理POST请求并返回响应。

前后端集成关键步骤总结

  • 跨域配置:必须确保后端CORS允许前端所在的域名/端口,否则请求会被浏览器拦截。
  • 端口一致性:后端服务启动端口需与前端baseUrl配置的端口一致,且无端口占用。
  • 模块依赖:Angular项目必须导入HttpClientModule才能使用HttpClient发起请求。
  • 路由匹配:前后端API路径需严格匹配,避免拼写或层级错误。
  • 请求方式匹配:前端使用的请求方法(POST/GET等)需与后端路由定义的方法一致。

内容的提问来源于stack exchange,提问作者Ajai Arjun

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 22:59:49