Home > Software engineering >  Fetch file content into string from url in Vue Js
Fetch file content into string from url in Vue Js

Time:02-17

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.

Best regards

CodePudding user response:

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

  • Related