Angular项目XMLHttpRequest无效URL错误求助及代码排查
Fixing the "Invalid URL" DOMException in Your Angular Service
Hey there, let's break down what's causing this error and fix it step by step!
The Core Issues
Looking at your CertificatenService code and the error message, two key problems are triggering the "Invalid URL" error:
Uninitialized
certificatenUrlvariable
You declaredprivate certificatenUrl: string;but never assigned a valid value to it. When thesave()method tries to use this variable as the request URL, it'sundefined—which makes the XMLHttpRequest throw the invalid URL exception.Mistakes in the
save()method- You're using the uninitialized
certificatenUrlinstead of following the same environment-based URL pattern you used infindAll(). - You're passing the class
Certificatenas the request body, instead of the actualcertificateninstance that's passed into the method.
- You're using the uninitialized
Corrected Service Code
Here's the fixed version of your service, with comments explaining the changes:
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Certificaten } from "../certificaten"; import { Observable } from "rxjs"; import { environment } from "../../../environments/environment"; @Injectable({ providedIn: 'root' }) export class CertificatenService { // Initialize the URL using your environment variable for consistency private certificatenUrl: string = `${environment.CVUrl}certificaten`; constructor(private http: HttpClient) { } public findAll(): Observable<Certificaten[]> { // Reuse the initialized certificatenUrl instead of repeating the environment call return this.http.get<Certificaten[]>(this.certificatenUrl); } public save(certificaten: Certificaten): Observable<Certificaten> { // Use the valid initialized URL, and pass the correct instance as the request body return this.http.post<Certificaten>(this.certificatenUrl, certificaten); } }
Quick Additional Checks
- Make sure
environment.CVUrlin yourenvironment.tsis a valid base URL (e.g.,http://your-api-endpoint.com/api/—ensure it ends with a slash if needed to avoid malformed URLs likeapiurlcertificaten). - Confirm your backend API is running and accessible at the target URL.
内容的提问来源于stack exchange,提问作者Joszsz
相关产品推荐
相关产品推荐

