Promise rejection caused by SyntaxError: Unexpected token i found in JSON at position 0 while trying to fetch a raw file from Gitlab

I'm attempting to retrieve a raw file from a Gitlab repository by following the official documentation.

Here are the functions in question:

  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%2Emd/raw?ref=master", "GET"))
        } catch (e) {
          rawFile = this.getProjects("https://gitlab.example.com/api/v4/projects/1/repository/files/readme%2Emd/raw?ref=master", "GET")
        }
      console.log(rawFile)
    }
  }

Upon logging the rawFile, it appears as a pending Promise object with a rejected state and a SyntaxError is displayed.

Could the issue be related to the raw format of the file causing this error? If so, how can this be prevented?

Answer №1

There are several factors at play here.

  • The domain gitlab.example.com is non-existent, making it challenging to determine the actual results you receive
  • You are providing the promise to JSON.parse. To utilize the response, you should use await or then:
  • At the end of your getProjects function, you are already parsing the JSON with response.json(). Additional parsing is unnecessary.

Consider using the following approach:

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

If the response is in json format, it will provide an object. However, if the response is not in json, utilize response.text() instead. You can create a separate function for this purpose:

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 proceed to call it like so:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fatal syntax error encountered when attempting to define a JavaScript object

Hey, I'm just starting out with JavaScript and I'm encountering a syntax error with the getValue() function in the code below. Can someone please assist me in solving it? let obj = { x:1, function getValue(){ console.log("hello") } } ...

Use jQuery to detect the presence of the class .class, and if it exists, automatically append the same class to a specific #id element on a particular webpage

Need help with jQuery - adding a specific class to an element based on the presence of another class Hello everyone, I have searched through various forums and tried multiple code snippets in JavaScript and jQuery to no avail. Despite other scripts worki ...

Navigate to a specific element using Selenium WebDriver in Java

Currently, I am utilizing Selenium along with Java and ChromeDriver to execute a few scripts on a website. My goal is to scroll the driver or the page to a specific element positioned on the webpage. It is important that this element is visible. I am awa ...

What is the best way to import a TypeScript file in index.js?

I've recently developed an application using the react-express-starter template. I have a "server" directory where the backend is created by nodejs, containing an index.js file: const express = require('express'); const app = express(); c ...

Cypress - simulate multiple responses for watchPosition stub

I have a small VueJs app where clicking on a button triggers the watchPosition function from the Geolocation API to retrieve the user's position and perform some calculations with it. Now, I want to test this functionality using Cypress testing. To ...

Material-UI exclusively incorporates specific components

Is there a way to include Material UI dialogs in my project without having to install the full Material UI library? I only need the dialogs component and don't want any other components included. Any suggestions or help on how to achieve this would be ...

Is it really necessary to still think poorly of JavaScript in 2011?

Here's an intriguing question for you. I've tested out a variety of popular websites, including Facebook, and I've noticed that many features still work perfectly fine even when JavaScript is disabled. People always used to say that JavaScr ...

Texture mapping in THREE.JS can be applied to ExtrudeGeometry for enhancing the appearance

Currently, I am tackling an issue concerning three.js and ExtrudeGeometry. The challenge at hand involves a wave-like structure composed of multiple individual frames, each being extruded using ExtrudeGeometry. https://i.sstatic.net/juEBb.jpg My goal is ...

A textarea with a height of zero is still visible

My goal is to create collapsible widgets within a side panel on my webpage. Overall, the functionality works smoothly. I am able to adjust the height of child divs to 0px with a transition, causing them to disappear. However, I have run into an issue wher ...

Using SVG Mask to enhance shape Fill

I am having trouble achieving the desired effect of darkening the fill of objects based on a specified gradient. Instead, when the mask is applied over the fill, it actually lightens it. I suspect that this issue arises from the color blending method being ...

Creating a soft focus effect in a specific region (behind the text)

While working on my homepage created with HTML/CSS/Javascript, I have text positioned at the top left corner of the screen. The challenge arises from the fact that I am using different backgrounds sourced from Reddit, and a script randomly selects one duri ...

Is there a glitch in the console when sorting an array of dates?

I'm puzzled by the fact that the console is displaying a sorted array in both logs. It doesn't make sense to me because it should not be sorted at the first log, right? static reloadAndSortItems() { let array = []; const items = Store. ...

Splitting the package.json file to separate the front-end and back-end components while utilizing shared

Currently, I am working on a project that involves a separate frontend (webpack) and backend (express/mongodb). My goal is to separate the dependencies in the package.json file while still being able to share certain logic/utility code between them. How ca ...

Issue with jQuery sortable serialization when dynamically adding content is not being recognized

I've been attempting to re-order a list through ajax on sortable update. However, when I add a new item to the list via ajax after the sortable has already been initialized upon page load, it fails to recognize the new item with the "serialize" functi ...

Tips for setting up a material-ui theme on the go

How can the material-ui theme object be dynamically configured? This feature is activated by clicking on the "set docs colors" button located on the documentation page of mui. ...

Enhance Your HTML Skills: Amplifying Table Display with Images

Recently, I utilized HTML to design a table. The Table Facts : In the first row, I included an appealing image. The second row contains several pieces of content. In continuation, I added a third row. The contents in this row are extensive, resulting i ...

Submitting a form via NextJS to an internal API

After reading through the Next.JS documentation, I came across an interesting point. Note: Instead of using fetch() to call an API route in getStaticProps, it's recommended to directly import the logic from within your API route and make necessary cod ...

Dynamic import of a SASS file in VueJS using a variable such as process.env

Is there a way to dynamically import a file using environment variables? I want to include a specific client's general theme SCSS to my app.vue (or main.ts) I'm thinking of something along the lines of: <style lang="sass"> @import"./th ...

I am attempting to retrieve the bot's permissions in order to validate if the command is authorized to execute

To verify if a command can be executed, I am attempting to retrieve the bot's permissions. Here is the code snippet I am using: let botid = "idbot" let bot = client.users.cache.get(botid) if (!bot.permissions.has("ADMINISTRATOR")) ...

Prompt for action following button activation

My goal is to set the focus on an input field when a button is clicked. I am attempting to do this by using a local directive called v-directive. However, I am encountering difficulties in getting the directive to apply properly after the button is clicked ...