how can i fetch a normal String to the data in Vue?

I am calling the following backend String : "hello there"

And as a frontend i am using Vue

<script>
export default {
  name: "test",
  data() {
    return {
      r:'',
      msg: '',
    };
  },
  methods: {
    loadMsg() {

    },
  },
  mounted () {
    var requestOptions = {
      method: 'GET',
      redirect: 'follow'
    };

    fetch("http://localhost:8080/api/v1/msgs/1", requestOptions)


        .then(response => response.json())
        .then(result => result.forEach(msg=> {
          this.msg.push(msg)
        }) )
        .catch(error => console.log('error', error));
  }
};
</script>

but I am getting the following error: error SyntaxError: Unexpected token h in JSON at position 0

However, when I use console.log() I get the massage on the console as expected.

What I want is just to pass the string to the data() to this.msg so is there any idea how to solve this problem ?


Solution 1:

You can only call .json() in a JSON response, apparently, your response is just plaintext

And another problem, your msg is a string (you are initializing it as ''), but the .push() is an Array method

Solution 2:

Considering that the content is hello there without quotes, the response not valid JSON, this will result in an error when a response is parsed.

response.text() should be used instead of response.json().