Angular中HTTP Get请求返回404错误:Collection 'joke'未找到
Angular中调用笑话API返回404:Collection 'joke' not found
问题描述
我刚开始学习Angular,想通过HTTP Get请求从笑话API获取内容。浏览器直接访问https://witzapi.de/api/joke能正常返回JSON格式的笑话,但在Angular应用中调用这个端点时,始终返回404错误,错误信息是「Collection 'joke' not found」。我查了Angular官方文档和相关教程,还是没解决问题。我的代码如下:
export class JokeCollectionService { joke: String | undefined; constructor( private http: HttpClient, ) { this.getJoke() } getJoke() { return this.http.get<any>('https://witzapi.de/api/joke').subscribe(data => { this.joke = data.text; }); } }
解决办法
尝试在请求中添加User-Agent请求头,模拟浏览器的请求标识:
首先导入HttpHeaders:
import { HttpHeaders } from '@angular/common/http';
然后修改getJoke方法:
getJoke() { const headers = new HttpHeaders({ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' }); return this.http.get<any>('https://witzapi.de/api/joke', { headers }).subscribe(data => { this.joke = data.text; }); }
补充检查项
- 确认已在
AppModule中导入HttpClientModule,否则HttpClient无法正常工作:
import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ // ...其他导入 HttpClientModule ] }) export class AppModule { }
- 验证API端点拼写完全一致,确保没有大小写或路径错误(你浏览器访问正常,这条大概率没问题)
内容的提问来源于stack exchange,提问作者Stefan
相关产品推荐
相关产品推荐

