You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目中HttpClient返回HTML而非JSON的问题求助

Angular请求返回HTML而非预期JSON的问题

我多次创建过Angular应用,此前均通过服务从MySQL数据库获取数据。但在当前新项目中,服务器返回的是HTML而非预期的JSON格式。尝试了多种方案都没效果,以下是相关代码:

Service代码 (test.service.ts)

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class TestService {
  constructor(private http: HttpClient) {}

  getUsers() {
    return this.http.get(`localhost/test/api.php/records/users`);
  }
}

组件代码 (beheer.component.ts)

import { Component, OnInit, inject } from '@angular/core';
import { TestService } from '../test.service';
import { CommonModule } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-beheer',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './beheer.component.html',
  styleUrl: './beheer.component.css',
})
export class BeheerComponent implements OnInit {
  constructor(private testService: TestService) {}

  ngOnInit() {
    this.getUsers();
  }

  getUsers() {
    this.testService.getUsers().subscribe((res) => {
      console.log(res);
    });
  }
}

浏览器开发者工具的网络面板显示响应类型为HTML,请问哪里操作出错了?


排查与解决办法

  • 请求URL缺少协议头:
    原代码中的请求地址localhost/test/api.php/records/users没有指定http://或https://,浏览器会将其解析为当前页面的相对路径,大概率指向了项目的HTML页面(比如404页面)。修改为完整URL:

    getUsers() {
      return this.http.get(`http://localhost/test/api.php/records/users`);
    }
    
  • 服务器接口返回错误页面:
    直接在浏览器地址栏访问完整的接口URL,查看返回内容。如果是HTML页面(比如404、500错误页),说明后端接口逻辑存在问题:可能是路径配置错误、权限验证失败、数据库查询异常,导致服务器返回了HTML错误页面而非JSON数据。需要检查api.php的代码逻辑,确保在正常和异常场景下都返回JSON格式响应。

  • 显式指定响应类型:
    尽管Angular的HttpClient默认期望JSON响应,但如果服务器返回的Content-Type头部不正确,可能导致解析异常。显式指定响应类型为JSON,强制HttpClient按JSON解析:

    getUsers() {
      return this.http.get(`http://localhost/test/api.php/records/users`, { responseType: 'json' });
    }
    
  • 检查跨域问题:
    如果Angular项目运行的端口(比如默认4200)和后端服务器端口不同,可能存在跨域限制。部分服务器在遇到跨域请求时会返回HTML格式的错误提示,而非JSON。需要在后端api.php中添加CORS相关头部:

    header("Access-Control-Allow-Origin: *"); // 生产环境建议指定具体域名
    header("Content-Type: application/json");
    

内容的提问来源于stack exchange,提问作者Jojoseph

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 18:35:10