• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

377
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error