1

I am working in WebStorm and I am trying to read a text file (file.txt) with JavaScript. I have tried doing this with Ajax, XMLHttpRequest and fetch but all of them returned an 404 error message.

This is my directory hierarchy:

directory hierarchy

NOTE: I am referring the file from artikels.js with the following code:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'data/file.txt', false);
xhr.onload = function() {
  if (this.status == 0) {
      const resp = this.response;
      console.log(resp);
  } else {
      console.log("fail");
}};
xhr.send();

I have been trying to alter the link to the following forms:

assets/js/own/data/file.txt
/assets/js/own/data/file.txt
./data/file.txt

How should I write the link in order to make it work?

SOLVED:

The mistake I made was that I build the path to the file.txt starting from the artikels.js file ... after trying the Location.pathname method (thanks to ibrahim tanyalcin for the advice) I found out that the current location was the location of the HTML-page that had a 'link' to the artikels.js file and not the artikels.js location ...

For illustration:

enter image description here

LazyOne
  • 158,824
  • 45
  • 388
  • 391
Edi
  • 11
  • 1
  • 3

1 Answers1

-1

The only absolute URL known to XMLHttpRequest() is URL of the document where this script runs.

So if you want to use relative URLs they should be relative to your document's URL.

Thus:

xhr.open('GET', 'assets/js/own/data/file.txt', false); 

Or you can use root relative URLs if assets folder is always at the root of your site:

xhr.open('GET', '/assets/js/own/data/file.txt', false); 
c-smile
  • 26,734
  • 7
  • 59
  • 86