获取请求在Angular 5 app中抛出404错误

壮心未与年俱老,死去犹能作鬼雄。这篇文章主要讲述获取请求在Angular 5 app中抛出404错误相关的知识,希望能为你提供帮助。
我是Angular的新手。我正在创建一个演示视频播放器应用程序,关注youtube系列,但我很惊讶我无法获取数据以获取我的获取请求。我正在使用Angular 5.2.10.Below是我的文件和代码:

  • server.js:
const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); const api = require('./server/routes/api'); const port = 3000; const app = express(); 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); });

  • api.js:
const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); const Video = require('../models/video'); const db="mongodb://usersubhash:subhashpwd@ds217350.mlab.com:17350/videoplayer"; mongoose.Promise = global.Promise; mongoose.connect(db,function(err){ if(err){ console.log("Error!"+err); } }); router.get('/videos',function(req,res){ //res.send('api works'); Video.find({}).exec(function(err,videos){ if(err){ console.log("error retrieving videos"); }else{ res.json(videos); } }); }); module.exports = router;

  • 的Video.js:
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const videoSchema = new Schema({ title:String, url:String, description:String }); module.exports = mongoose.model('video',videoSchema,'videos');

  • video.ts:
export class Video { _id:string; title:string; url:string; description:string }

  • environment.ts
export const environment = { production: false, apiUrl: 'http://localhost:3000' };

  • video.service.ts :(其中我有getVideos()方法)
import { Injectable } from '@angular/core'; import {Http,Response} from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class VideoService {constructor(private _http:Http) { } private _getUrl = `${environment.apiUrl}/api/videos`; getVideos(){ return this._http.get(this._getUrl).map((response:Response)=> response.json()); } }

  • videoCenter.component.ts :(我订阅了getVideos()方法):
import { Component, OnInit } from '@angular/core'; import {Video} from '../video'; import { VideoService } from '../video.service'; @Component({ selector: 'app-video-center', templateUrl: './video-center.component.html', styleUrls: ['./video-center.component.css'], providers:[VideoService]//,Http,HttpClientModule }) export class VideoCenterComponent implements OnInit { myAllVideos:Array; //here I want to put my get Request Data constructor(private _videoService:VideoService) { }selectedVideo:Video; onSelectVideo (video:any){ this.selectedVideo=video; }ngOnInit() { this._videoService.getVideos().subscribe(result => this.myAllVideos = result); }}

【获取请求在Angular 5 app中抛出404错误】我跑的时候
node server.js

in VSCode terminal , then in POSTMAN app I can get all records by requesting GET in "localhost:3000/api/videos".But in my app, I am unable to load data which is running in 4200 port. When I click on button which loads video-center.component.ts , getVideos() is triggered in ngOnInit() but it throws this error:
获取请求在Angular 5 app中抛出404错误

文章图片
获取请求在Angular 5 app中抛出404错误

文章图片
答案显示错误的屏幕截图有这个网址:
http://localhost:4200/api/videos
但是你的server.js说:
const port = 3000;

所以你的服务器在端口3000上运行,而不是4200.端口4200通常是Angular运行的地方。
所以你需要修改你的getUrl:
private _getUrl = "http://localhost:3000/api/videos";

我建议您阅读如何设置environment文件,并将主机部分“http://localhost:3000”放在环境文件中并从那里读取,而不是硬编码。然后你的代码可能是:
private _getUrl = `${environment.apiUrl}/api/videos`;

注意
需要明确的是 - 虽然Angular在客户端运行,但它是一个必须从某个地方启动的应用程序。例如,在生产情况下,您可能会这样:
https://app.mydomain.com
https://api.mydomain.com
在生产中,很可能这两个网址都可以在端口80上访问。但是由于子域名不同(apiapp)完全没问题。
但是,在开发模式下本地运行时,您无法在具有相同端口的同一地址(localhost)上运行两个不同的东西(即Angular应用程序和Node应用程序)。
由于您在localhost上运行它们,因此它们必须具有不同的端口。所以当你写道:
return this._http.get(this._getUrl)...

它默认为Angular本身运行的地方,localhost:4200,而不是你的api。您需要告诉角度你的api在3000端口。

    推荐阅读