What is the best way to deal with a "Access to restricted URI denied" error in JavaScript while utilizing XMLHttpRequest?

Here is some code I am working with:

var req = new XMLHttpRequest();
req.onload = function(){
    if (req.status === "200"){
        doSomethingWithTheReceivedData();
    }
    else {
        alert("Error msg");
    }
};

When running index.html directly from my computer without a server, I encountered the error "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied" in the Firefox web console. This is because the script was trying to access a relative path that is only available on the server, not locally on my computer. Now, I need to properly handle this error situation as currently, clicking the button triggering this code does nothing. Despite adding a status code check, it doesn't seem to address this particular issue. I assume no request is returned in this case. So, how can I effectively manage and respond to this error?

Answer №1

Implement a try-catch block when initiating the send of the request:

try{
  req.send(null);
}catch(e){
 alert(e.message);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble finding a solution to prevent code from automatically adding a class in jQuery/JavaScript?

I am currently in the process of customizing the FlexNav Plugin. I have made a modification to allow sub-menus to open on click instead of hover. However, a new issue has arisen where it requires two clicks to open a submenu. Upon investigation, I have i ...

Simulating server-side interactions in Node.js with TestCafe

I am currently working on a project where I need to figure out how to mock server-side requests. While I have successfully managed to mock client-side requests using request hooks, I am facing challenges when it comes to intercepting server-side requests ...

Node.js: Promise chain abruptly stops after reaching a predefined limit without causing any errors

Currently, I am attempting to perform a straightforward operation in nodejs using promises. My task involves working with an array that consists of objects. These objects contain query parameters for a URL that I need to access through a GET request. As th ...

Initializing an Express app with JSON file loading

My movie-finding application relies on backend API calls to function. As part of the initialization process, I need to load two JSON files: one containing a list of languages for searching (lang.json) and another stored in the config variable that provides ...

Convert the dynamic table and save it as a JSON file

Looking for the most effective method to save dynamic table data into JSON format. I have two tables that need to be saved into a single JSON file. While I can easily access and console log the regular table data, I'm having trouble retrieving the td ...

Extract data from the Ajax database and automatically hide the "Load More" button when all items

Every time I fetch data from my MySQL database, I retrieve 5 items at once. $query = $pdo->prepare("SELECT * FROM names WHERE id < ? ORDER BY id DESC LIMIT 5"); $query->execute([$_POST["id"]]); while($row = $query -> fetch() ...

Updating the value of the variable using ng-submit

My application displays Quantity: {{num}}. The default value is set to 3 in the scope. The objective is to click on: <form ng-submit="addContact()"> <input class="btn-primary" type="submit" value="Add Contact"> </form> and to up ...

Generating unique spreadsheet identifiers in an HTML file

When it comes to displaying a chart using Google Sheets, I encounter an issue where the data is sourced from the same spreadsheet: function updateChart() { var ui = HtmlService.createHtmlOutputFromFile('ChartLine').setWidth(1350).setHeight(550) ...

What is the best method to retrieve child elements from a class list object?

Seems like I have a similar content class <div class="parentclass"> <div class="childClass"> </div> <div class="childClass"> </div> <div class="childClass"> </d ...

What is the reason behind TypeScript enclosing a class within an IIFE (Immediately Invoked Function

Behold the mighty TypeScript class: class Saluter { public static what(): string { return "Greater"; } public target: string; constructor(target: string) { this.target = target; } public salute(): string { ...

Form submission is not possible while the login form is active

I'm encountering an issue where I am unable to trigger - ng-submit or ng-click on this code except for the local onclick function on the login button. If you have any insights or solutions, please share them: <form ng-submit = "login.submitLogin ...

What is the best way to pass an array through router navigate function?

I've searched for a solution in other questions, but nothing has helped me... My goal is to redirect to a URL like this: this.router.navigateByUrl('/products'); I want to pass an array and retrieve it in the component with the active link ...

Ensure that the dropdown menu remains visible even after the mouse no longer hovers over it

Looking to create a main menu with dropdown items that appear when the user hovers over them? You may have noticed that typically, the dropdown disappears once the hover event is lost. But what if you want the menu to stay visible and only disappear upon c ...

I need help figuring out how to set the country code as uneditable and also display a placeholder in react-phone-input-2 with React

How can I display the placeholder after the country code without allowing it to be edited? Currently, it's not showing up in my React functional components. Here is the code snippet: <PhoneInput className="inputTextDirLeft" ...

How can a callback be properly passed in programming?

My coding approach is outlined below: var CustomLibrary = (function (window, $, undefined) { return { URI: 'http://testpage/API/', OnSuccess: function (data, status) { }, OnError: function (request, status, error) { } ...

Enhancing my code by implementing various conditions in React

Looking for ways to enhance my code quality (Very Important, Important, Medium, Low, Good, Excellent,...) : { Header: "Opinion", accessor: (row) => row.opinion, Cell: props => <span> {props.value == ...

Issues with UA PhoneGap 2.0 plugin failing to initialize properly on iOS device

In my attempt to integrate push notifications into my iOS PhoneGap 2.0 app using the recently released Urban Airship plugin, I encountered an issue. Everything functions perfectly when I load the index.html from the provided sample application into my proj ...

File or directory does not exist: ENOENT error encountered when attempting to access 'distrowserindex.html'

Upon executing ng deploy --preview, an error is encountered: Error: ENOENT: no such file or directory, open 'dist\index.html' at Object.openSync (fs.js:457:3) at readFileSync (fs.js:359:35) Despite attempting various online tutorial ...

Press the Enter key to generate a new table row

I have been dynamically creating an HTML table. Each row contains two columns created through a recursive call. Currently, a new row is generated by clicking on the second cell, but I want to switch this action to the "Enter" key press. Although my code su ...

The v-list-group does not automatically expand sub-groups based on the path specified in the group prop

I have a navigation sidebar that includes nested v-list-groups. Based on the documentation, the "group" prop of v-list-group should expand based on the route namespace. To see more information, visit: https://vuetifyjs.com/en/components/lists/ While this ...