【发布时间】:2019-02-03 03:09:42
【问题描述】:
我正在为 Angular 开发一个国际化库,我想制作一个 Angular 组件,它返回给定语言的所有翻译。只是为了测试我创建了以下 TranslateComponent
import {Component} from '@angular/core';
@Component({
selector: 'trans-translate',
templateUrl: './translate.component.html'
})
export class TranslateComponent {
// region Public fields
public data: string[] = ['This', 'is', 'Sparta'];
// endregion
}
使用简单的html模板显示数据:
{{ data | json }}
访问该组件的 url 是 http://localhost:4200/translate,如果我从浏览器访问它,一切都很好(我有以下结果:[“This”,“is”,“Sparta”] 显示。 问题是我想用 HttpClient 调用它,但它不起作用。我只是做了这个简单的测试:
import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Component({
selector: 'app-page-test',
templateUrl: './test-page.component.html'
})
export class TestPageComponent implements OnInit {
// region Constructor
public constructor(
private readonly _HTTP: HttpClient
) {}
// endregion
// region Public methods
public ngOnInit(): void {
this._HTTP.get('/translate').subscribe((result: any): void => {
console.log(result);
});
}
// endregion
}
但我得到的只是正文的错误 404:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /translate</pre>
</body>
</html>
我无法弄清楚我错过了什么?它是我必须添加到请求中的标头吗?
为了记录,我实际上使用的是 Angular 7,我使用命令“npm run start”启动服务器,该命令基本上只是执行 tu“ng serve”命令。
【问题讨论】:
-
您是否在服务器上启用了跨域资源共享 (CORS)?
-
是同一台服务器。这是页面localhost:4200/test 向localhost:4200/translate 发出请求,所以我为什么会有问题,
-
您的请求的网址是什么样的。只是想知道,因为通常 ng serve 在
localhost:4200上运行,并且您想在您的请求中定位localhost:4000 -
这只是我原帖中的一个错误,我真的调用了4200端口
标签: angular http request localhost