【问题标题】:Ajax call to an angular app returns an error 404 on existing route对 Angular 应用程序的 Ajax 调用在现有路由上返回错误 404
【发布时间】: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/testlocalhost:4200/translate 发出请求,所以我为什么会有问题,
  • 您的请求的网址是什么样的。只是想知道,因为通常 ng serve 在localhost:4200 上运行,并且您想在您的请求中定位localhost:4000
  • 这只是我原帖中的一个错误,我真的调用了4200端口

标签: angular http request localhost


【解决方案1】:

翻译和测试是两个组件。 localhost:4200/translate 实际上是一个组件,显示数据。

而在测试页面中,您尝试使用 HttpClient 调用服务。它不会调用翻译组件并返回数据。

希望这就是你提到的意思

t 是页面 localhost:4200/test 发出请求 localhost:4200/translate 所以我为什么会有问题

【讨论】:

  • 其实我想调用服务器(TestCompont会在浏览器中使用,但是TranslateComponent应该在后端执行)
猜你喜欢
  • 2014-12-23
  • 1970-01-01
  • 2017-09-08
  • 2016-05-26
  • 1970-01-01
  • 2022-12-25
  • 2021-02-21
  • 1970-01-01
  • 2021-12-16
相关资源
最近更新 更多