Angular HTTP Get请求失败求助:JSON解析错误排查
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 inHttpClient.get()points directly to your JSON file. For example, if your file is in thesrc/assetsfolder (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.jsonassets configuration
Angular only includes files in theassetsarray in your build output. If your JSON file isn't in a directory listed here, it won't be available when your app runs. Openangular.jsonand 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

