Home > Enterprise >  XMLHttpRequest is not defined in frontend code
XMLHttpRequest is not defined in frontend code

Time:05-02

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related