Angular 5应用中GET请求抛出404错误的问题求助
解决Angular 5调用Express API出现404的问题
看起来你遇到的是前端跨域请求限制导致的典型问题——Postman能正常请求后端API,但Angular应用却返回404,下面一步步帮你排查解决:
1. 优先解决跨域问题(最可能的根源)
浏览器会阻止不同端口的前端应用直接请求后端API(你的Angular跑在4200端口,后端在3000端口),而Postman不受浏览器的跨域限制。给Express后端添加CORS中间件就能解决这个问题:
- 首先安装
cors依赖包:
npm install cors --save
- 修改你的
server.js,引入并启用CORS中间件:
const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); const api = require('./server/routes/api'); const cors = require('cors'); // 新增引入CORS包 const port = 3000; const app = express(); app.use(cors()); // 新增启用CORS,放在所有中间件最前面 app.use(express.static(path.join(__dirname,'dist'))); app.use(bodyParser.urlencoded({extended:true})); app.use(bodyParser.json()); app.use('/api',api); app.get('*',(req,res)=>{ res.sendFile(path.join(__dirname,'dist/index.html')); }); app.listen(port,function(){ console.log("server running on localhost"+port); });
2. 检查Angular Http模块的导入
Angular 5的Http服务需要在根模块中导入HttpModule才能正常工作,你可能遗漏了这一步:
打开app.module.ts,将HttpModule添加到imports数组中:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpModule } from '@angular/http'; // 引入HttpModule import { AppComponent } from './app.component'; import { VideoCenterComponent } from './video-center/video-center.component'; @NgModule({ declarations: [ AppComponent, VideoCenterComponent ], imports: [ BrowserModule, HttpModule // 添加到这里 ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
注意:不需要在VideoCenterComponent的providers里添加Http或HttpClientModule,根模块导入后整个应用都能使用Http服务。
3. 修正组件和服务的细节问题
- 在
video-center.component.ts中,给myAllVideos指定正确的类型,避免类型错误:
myAllVideos: Array<Video>; // 替换原来的Array类型
- 在
video.service.ts中,可以添加日志确认请求URL是否正确:
private _getUrl = `${environment.apiUrl}/api/videos`; constructor(private _http:Http) { console.log('当前请求URL:', this._getUrl); // 应该输出http://localhost:3000/api/videos }
4. 重启服务测试
完成上述修改后,分别重启你的Express后端和Angular应用:
- 停止当前运行的
node server.js,重新启动后端服务 - 停止
ng serve,重新启动Angular开发服务
现在再触发ngOnInit中的请求,应该就能正常获取数据了。如果仍有问题,打开浏览器开发者工具的Network标签,查看请求的具体URL和响应详情,确认是否真的是404,还是有其他错误提示。
内容的提问来源于stack exchange,提问作者Subhash Chaganti
相关产品推荐
相关产品推荐

