• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

372
Vistas
XMLHttpRequest is not defined in frontend code

I get this error from

<script lang="ts">
    import { onMount } from "svelte";

    const xhr = new XMLHttpRequest();

    let url = "";

    onMount(() => url = window.location.href.substr(31)); //get query

    xhr.open("GET", url);

    xhr.onload = () => {
        let resp = xhr.response;
    }

    xhr.send();
</script>
{resp}

the error is

ReferenceError: XMLHttpRequest is not defined

I am using svelte, and all the questions about this error are about backend node.js code.

almost 3 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

first of all why you are not using fetch instead of XMLHttpRequest?

Secondly XMLHttpRequest is not available in node so this is probably the reason why you are obtaining this error.

According to documentation all external calls should be done in onMount hook. Thank to this such calls will be executed only on client side (where XMLHttpRequest is available).

Additionally resp variable is available only inside onLoad handler so it is not possible to render it currently in your code. So it should look probably like this:

<script lang="ts">
    import { onMount } from "svelte";

    let resp = 'Loading...'
    onMount(() => {
           const url = window.location.href.substr(31); //get query
           const xhr = new XMLHttpRequest();
           xhr.open("GET", url);

           xhr.onload = () => {
              resp = xhr.response;
           }

           xhr.send();
     });
</script>
{resp}

But I recommend to do refactor and use fetch. At the end, it might be more elegant, to work with query params like below:

let url = '';
const href = new URL(window.location.href);
const params = new URLSearchParams(url.search);
if (params.has('paramName')) {
    url = params.get('paramName')
}

Mateusz

almost 3 years ago · Juan Pablo Isaza Denunciar

0

You might need to adjust your tsconfig.json and ensure that "dom" has been added to the lib option. If for some reason the DOM type library is not included, the type will be missing, causing errors when using TypeScript.

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda