Retrieve a remote text file using vanilla JavaScript instead of relying on jQuery

Currently, I am aiming to retrieve the content of a text file using JavaScript for parsing purposes. Although I previously relied on jQuery and JSONP for this task, I now prefer to achieve it without any framework.

Despite numerous attempts, none have been successful so far. Here is my latest attempt:

var url = 'https://url.com/videosList.txt';

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = process;
xhr.open("GET", url, true);
xhr.send();

function process()
{
  if (xhr.readyState == 4) {
    console.log(xhr.responseText);
  }
}

The code appears to be correct, but my Chromium browser consistently presents the following error message:

> XMLHttpRequest cannot load
> https://url.com/videosList.txt. Origin
> http://localhost:8888 is not allowed by Access-Control-Allow-Origin.

Answer №1

By default, Cross-Site Scripting is restricted under the standard security settings. Your code will only function properly if the requested URL belongs to the same domain as the originating page.

If you have authority over the remote server, you can include a specific header in the response:

Access-Control-Allow-Origin: *

However, XMLHttpRequest behavior varies between browsers (especially IE), so using a "library shim" may be necessary to ensure consistency across different platforms. It's recommended to use jQuery for ease of implementation :)

For further information, check out these resources:

Have a great coding journey!

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

On-page refresh triggering HTTP 404 error in Vue3 routing situation

Issue Upon reloading a route, such as /installer, in Vue3.js, I encounter the following error: https://i.sstatic.net/UKxdk.png Code Snippet I am utilizing the Router with the setup below: const router = createRouter({ history: createWebHistory(proces ...

Organizing the website's files and extensions

Transitioning from programming desktop applications to websites can be overwhelming, especially when dealing with multiple languages and extensions like JavaScript, CSS, JSON, Bootstrap, Ajax, and PHP all at once. How do you effectively juggle these diff ...

Communicating the outcome of AJAX calls from Asp.Net Web API: sending success or failure status

For my current project involving an asp.net C# Web API, I am facing issues with posting data from a client using jQuery AJAX. Despite trying two different types of AJAX calls, the code never reaches the success or error functions in the AJAX. Asp.Net Web ...

How can constants from components be defined in multiple ways when imported? (specifically in React)

Although I have a good understanding of React and Javascript, I struggle to articulate my question effectively. I will provide examples in the hopes that someone with more expertise in the field can assist me. For instance, when using import { useRef, use ...

leveraging UI-Router for navigating based on app state and data

Is there a way to dynamically adjust Angular's ui-routing based on certain data conditions? For instance, let's say we need to create a subscription process where the user is informed of whether their subscription was successful or not. As the f ...

Asynchronous JavaScript function within a loop fails to refresh the document object model (DOM) despite

I have been working on a function that utilizes ajax to retrieve instructions from a backend server while the page is loading. The ajax code I've written retrieves the instructions based on the number provided and displays them using the response.setT ...

Tips on implementing Piwik JavaScript code within app.js on Express

I am trying to implement Piwik tracking on my Express website using JavaScript code. I placed the code in my app.js file but encountered an error. Here is the JavaScript code snippet: <script type="text/javascript"> var _paq = _paq || []; ...

Which is superior: Evaluating AJAX Treeview versus GridControls from various vendors?

After working solely with ComponentArt controls, I am curious to explore other options. Which Grid and Treeview controls are worth looking into? I am open to paying for them as long as they offer quality, speed, and reliability. While I have noticed some ...

Is it permissible to make alterations to npm modules for node.js and then share them publicly?

I have made modifications to a module called scribe.js that I use in my own module, which is published on npm. Instead of using the original module as a dependency for my module, I would like to include my modified version. I am unsure about the legal impl ...

I am experiencing an issue with environment variables not appearing in my Context component on Next.js. Should I adjust the Next.js configuration or set up the Context to properly utilize the variables?

Why are Environment Variables working on every component inside /pages but not in my Context component in Next.js? Do I need to do some configuration in Next.js for this? (Note: The Shopcontext.tsx file is using a class component that I obtained from a tu ...

Implementing phone verification code delivery using ReactJS and Twilio client: Step-by-step guide

I've been scouring the internet for the past 8 hours and haven't been able to find a tutorial on using Twilio to send SMS messages with ReactJS. Does anyone know of a good tutorial for this? ...

Having trouble with Express router behaving unexpectedly in a subdirectory

In my Node.js app, I have organized my API queries by modules. This structure is reflected in the index.js file as follows: app.use('/api/schedule/', apiSchedule); Within the apiSchedule router, I have defined different route handlers: router. ...

Adjusting the width of innerHtml within a React router link to match the parent element's width

My current challenge involves a table where a cell is represented as a link. Within this setup, I am incorporating html content into the text of the link: <TableCell align="left" classes={{root: classes.cellPadding}}> <Link className={classes.l ...

Unable to submit form data in AWS Amplify & React: The message "Not Authorized to access createRecipe on type Mutation" is displaying

I've recently set up a project using React and AWS Amplify. I've successfully added some data to DynamoDB in AWS, but when I try to submit form data from my React App, I encounter an error from the API. I'm a bit stuck on what to do next. I ...

Self-referencing object identifier

Having trouble articulating this question, but I'm attempting to develop a JavaScript object that manages an array of images for reordering and moving purposes. function imgHandler(divname) { this.imgDiv = divname; this.img = Array("bigoldliz ...

Create a modal using the base of a[href^=“#id”]

What is the best way to minimize a call modal window? $('#button-1').on('click', function() { $('#modal-1').addClass('j-modal--open'); }); $('#button-2').on('click', function() { $(' ...

Manipulating front matter metadata when reading/writing a markdown file in Node.js

I have a large collection of markdown files that I need to update by adding new data to their front matter metadata. Currently, the file structure looks like this: --- title: My title here --- Markdown content here My goal is to include an id property ...

Apologies, we are experiencing a server error. TypeError: Unable to access the 'map' property of an undefined

I'm struggling to grasp the concept of fetching external data using server-side rendering with the getServerSideProps method. In particular, I am facing difficulties with the search functionality and how to handle the returned data. As someone who is ...

"Exploring the world of Mean.js with Node.js background functionalities

Struggling with my mean.js app as I try to figure out how to implement background processes. I want these processes to run continuously, interacting with the mongodb database and handling tasks like cleanup, email notifications, and tweets. I need access ...

An Axios error message indicates ERR_NETWORK and ERR_EMPTY_RESPONSE

When I initiate a Patch Request from the frontend, it takes approximately 30-40 seconds for the backend to resolve. const handleSendClick = (data: any) => { const requiredLanguages = Array.isArray(data.required_languages) ? data.required_langu ...