Home > Blockchain >  Rejected promise with SyntaxError: Unexpected token i in JSON at position 0 when fetching raw file f
Rejected promise with SyntaxError: Unexpected token i in JSON at position 0 when fetching raw file f

Time:10-15

I'm trying to fetch a raw file from Gitlab repository, following official documentation.

The functions are the following:

  methods: {
    async getProjects(url, method, payload) {
      const token = this.$store.getters.token
      const headers = {
        'Content-Type': 'application/json',
        'Private-Token': token
      }

      const response = await fetch(url, {
        method: method,
        headers: headers,
        body: JSON.stringify(payload)
      })
      return response.json()
    },
    [...]
    async addNewProject() {
      const payload = {
        "name": "newProjectName",
        "namespace_id": 12,
        "description": "description"
      }
      
      this.getProjects("https://gitlab.example.com/api/v4/projects/", "POST", payload)
        .then(data => {
          console.log(data.id)
        })
        .catch((e) => {
          console.error(e)
        })
        
      let rawFile = null
        try {
          rawFile = await JSON.parse(this.getProjects("https://gitlab.example.com/api/v4/projects/1/repository/files/readme.md/raw?ref=master", "GET"))
        } catch (e) {
          rawFile = this.getProjects("https://gitlab.example.com/api/v4/projects/1/repository/files/readme.md/raw?ref=master", "GET")
        }
      console.log(rawFile)
    }
  }

Logging the rawFile shows a pending Promise object with rejected state and the SyntaxError as in the title.

Is it possible that the raw format of the file is causing this error? If so, how to prevent it?

CodePudding user response:

There are a few things going on.

  • gitlab.example.com doesn't exist, so it's difficult to know what results you actually get
  • You are passing the promise to JSON.parse. You need to use await or then to use the response:
  • The end of your getProjects calls response.json() which will parse the json. You don't need to parse it again.

How about using:

let rawFile = await this.getProjects("https://gitlab.example.com/api/v4/projects/1/repository/files/readme.md/raw?ref=master", "GET")

If the response is json, that would give you an object, but if the response is not json, you want to use response.text() instead. You'd need a different function:

async getTextFile(url) {
      const token = this.$store.getters.token
      const headers = {
        'Private-Token': token
      }

      const response = await fetch(url, {
        method: "GET",
        headers: headers
      })
      return response.text()
    }

then call it like this:

let rawFile = await this.getTextFile("https://gitlab.example.com/api/v4/projects/1/repository/files/readme.md/raw?ref=master")
  • Related