简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM