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?

1
  • It's not returning JSON, remove the .then(res => res.json()) to see what it is actually returning. Commented Oct 18, 2019 at 13:38

1 Answer 1

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")

Sign up to request clarification or add additional context in comments.

5 Comments

right it should be into the assets dir. To do that I would probably use a symbolic link.
maybe I should have not used package.json as example, but originaly I use "assets/projects.json" and same error occured
And what do you get when visiting the url directly? something like localhost:3000/assets/projects.json?
@Vanz Added to my answer according to your comment
@red-X when I visit localhost:8080/assets/projects.json nothing is showing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.