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

Angular HTTP Get请求失败求助:JSON解析错误排查

Fixing the "Unexpected token < in JSON at position 0" Error in Angular HTTP Requests

Hey there! Let's break down why you're seeing this frustrating error and how to fix it.

What's causing this error?

This error pops up because your Angular app is trying to parse the response from your HTTP request as JSON, but the server actually sent back HTML content (like a 404 error page, or your app's index.html) instead. The JSON parser hits the < at the start of the HTML and doesn't know what to do with it.

Common fixes to try:

  • Double-check your JSON file path
    Make sure the path you're using in HttpClient.get() points directly to your JSON file. For example, if your file is in the src/assets folder (the standard place for static files in Angular), your request should look like this:

    this.http.get('./assets/your-data-file.json').subscribe(data => {
      console.log('Loaded data:', data);
    });
    

    If the path is wrong, the server will return a 404 HTML page instead of your JSON, triggering the error.

  • Verify your angular.json assets configuration
    Angular only includes files in the assets array in your build output. If your JSON file isn't in a directory listed here, it won't be available when your app runs. Open angular.json and make sure your assets folder is included:

    "assets": [
      "src/favicon.ico",
      "src/assets"
    ],
    

    If you added a custom folder for JSON files, add it to this array too.

  • Add error handling to see the actual response
    To confirm what's being sent back, add error handling to your request. This will let you view the raw HTML response and pinpoint the issue:

    import { catchError } from 'rxjs/operators';
    import { throwError } from 'rxjs';
    
    // ...
    
    this.http.get('./assets/your-data-file.json')
      .pipe(
        catchError(err => {
          console.error('Request failed:', err);
          console.error('Raw response:', err.error); // This will show the HTML content
          return throwError(() => new Error('Failed to load data'));
        })
      )
      .subscribe(data => {
        console.log('Loaded data:', data);
      });
    

Quick recap

The root issue is that your HTTP request isn't returning valid JSON—instead, it's getting HTML. Start by fixing your file path and confirming your assets are configured correctly, then use error handling to debug further if needed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:21:39