【问题标题】:Angular Service making Http requests to localhost:4200 instead of localhost:8080Angular Service 向 localhost:4200 而不是 localhost:8080 发出 Http 请求
【发布时间】:2022-01-09 21:46:16
【问题描述】:

我有一个 Angular + Spring Boot 项目。 Angular 项目包含向运行在端口 8080 上的 Spring Boot 应用程序发出 Http 请求的服务。当我尝试在服务环境中使用 apiBaseUrl 变量时,我得到如下 404 状态:

services 正在对 localhost:4200 而不是 localhost:8080 进行 Http 调用

环境:

export const environment = {
production: false,
apiBaseUrl: 'http://localhost:8080'
};

服务:

import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { environment } from "src/environments/environment";
import { Student } from "./student";

@Injectable ({
providedIn: 'root'
})

export class StudentService {


private apiServerUrl = environment.apiBaseUrl;

constructor(private http: HttpClient) { }

public getStudents(): Observable<Student[]> {

  return this.http.get<Student[]>('${this.apiServerUrl}/student');

}
 //rest of code

但是当我进行更改并直接提供 url 时,一切正常。

return this.http.get<Student[]>('http://localhost:8080/student');

谁能给我解释一下,这是我的第一个 Angular 应用程序,所以谢谢你的理解

【问题讨论】:

    标签: angular spring-boot http-status-code-404


    【解决方案1】:

    你应该使用反引号`,而不是单引号'

      return this.http.get<Student[]>(`${this.apiServerUrl}/student`);
    

    【讨论】:

    • 我不敢相信我花了这么多时间才弄明白。你节省了我很多空闲时间。再次感谢
    • 很高兴为您提供帮助。如果代码符合您的要求,您能否将答案标记为已回答?
    【解决方案2】:

    为了解决这个问题,您可以通过 `` 在这一行中更改 '' this.http.get('${this.apiServerUrl}/student');

    正确的代码是:

    this.http.get<Student[]>(`${this.apiServerUrl}/student`);
    
    

    或者

    this.http.get<Student[]>(this.apiServerUrl+ '/student');
    
    

    【讨论】:

    • 现在我知道了,这是我使用 Angular 的第一步。谢谢!!
    • 不客气,干得好
    猜你喜欢
    • 2021-06-28
    • 2022-01-26
    • 1970-01-01
    • 2020-05-08
    • 2020-11-30
    • 1970-01-01
    • 2021-04-20
    • 2019-06-04
    • 2018-01-08
    相关资源
    最近更新 更多