0

I am practicing fetch Api, and trying to get the data of projects.json file in my vue-cli project and to show it on console.

Project architecture:

src/views/Projects.vue
src/assets/projects.json

Projects.vue in created method we fetch the json data

<template>
  <div>
    <h1>Hello WOrld</h1>
  </div>
</template>

<script>
export default {
  name: "projects",
  created() {
    fetch("../assets/projects.json")
      .then(res => res.json())
      .then(data => {
        console.log(data);
      })
      .catch(err => {
        console.log(err);
      });
  }
};
</script>

when load the component Syntax Error is shown.

SyntaxError: Unexpected token < in JSON at position 0

projects.json contains just the basics

    {
  "projects": [
    {
      "id": 1,
      "title": "pie station"
    },
    {
      "id": 1,
      "title": "automate dryer"
    }
  ],
  "profile": {
    "name": "someaone"
  }
}

How can I show in console the content of my .json file using fetch Api?

Evan
  • 2,327
  • 5
  • 31
  • 63
  • It's not returning JSON, remove the `.then(res => res.json())` to see what it is actually returning. – zero298 Oct 18 '19 at 13:38

1 Answers1

1

Look for the network tab in the console, you'll probably notice that your fetch call is returning a 404 html page. The server is most likely not serving the package.json but that depends on your setup. (you normally wouldn't want to serve it anyway)

Are you running a default vue cli environment with an npm run serve? If so you can add a json file in the assets dir, this should be served normally and it can be fetched at /assets/{insert the rest of the path here}.

EDIT

Say you have projects.json in the assets dir like you mentioned in the comments you should be able to access it with fetch("/assets/projects.json")

red-X
  • 5,108
  • 1
  • 25
  • 38
  • right it should be into the assets dir. To do that I would probably use a symbolic link. – Loïc Oct 18 '19 at 13:38
  • maybe I should have not used package.json as example, but originaly I use "assets/projects.json" and same error occured – Evan Oct 18 '19 at 13:43
  • And what do you get when visiting the url directly? something like `localhost:3000/assets/projects.json`? – red-X Oct 18 '19 at 13:45
  • @Vanz Added to my answer according to your comment – red-X Oct 18 '19 at 13:48
  • @red-X when I visit localhost:8080/assets/projects.json nothing is showing – Evan Oct 18 '19 at 13:59