Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fetch file content into string from url in Vue Js

I’m getting into vue js right now. Currently I’m trying to get data from an external file (from another server, from url) into a string to parse it into an array. But I’m already failing with the file to string part. I tried using:

export default {
data() {
    return {
      lines: [],
      error: '',
      choice: '',
      content: ''
    }
async created() {
    try{
      parseFile();
    }
    catch(err){
      this.error = err.message;
    }
methods: {
    async parseFile() {
      fetch('https://filesamples.com/samples/document/txt/sample3.txt')
        .then(response => response.text())
        .then(data => {console.log(data); this.content = data;});
    }
  }
}

Which I want to store into content as a string to split it up later into the lines array.

Sadly it doesn’t even load, I will always get nothing in the console. Why might this be? I found in here that you can use raw-loader (or the asset modules now i think) to import a raw file into vue. But it’s not my aim to import the raw file into the App.vue to load it. Does anybody have an Idea, why this is not working for me? I’m not so much used to JavaScript, maybe I’m just dumb or so, lol.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Best regards

>Solution :

There is nothing wrong with your code, you are using a promise chain to get the result of the fetch, but you’re getting a CORS error on the request which isn’t captured.

I have changed the format of the code and added an extra try catch you will see ‘error in fetch’ logged to the console.

async parseFile() {
   try {
     const fetchResponse = await fetch(
       "https://filesamples.com/samples/document/txt/sample3.txt"
     );
     console.log(fetchResponse.text());
   } catch (ex) {
     console.log("Error in fetch");
   }
}

https://codepen.io/DanielRivers/pen/qBVpZOo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading