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

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:

  1. Uninitialized certificatenUrl variable
    You declared private certificatenUrl: string; but never assigned a valid value to it. When the save() method tries to use this variable as the request URL, it's undefined—which makes the XMLHttpRequest throw the invalid URL exception.

  2. Mistakes in the save() method

    • You're using the uninitialized certificatenUrl instead of following the same environment-based URL pattern you used in findAll().
    • You're passing the class Certificaten as the request body, instead of the actual certificaten instance that's passed into the method.

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.CVUrl in your environment.ts is a valid base URL (e.g., http://your-api-endpoint.com/api/—ensure it ends with a slash if needed to avoid malformed URLs like apiurlcertificaten).
  • Confirm your backend API is running and accessible at the target URL.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:55:55