Estoy tratando de obtener un archivo sin procesar del repositorio de Gitlab, siguiendo la documentación oficial.
Las funciones son las siguientes:
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) } } El registro de rawFile muestra un objeto Promise pendiente con estado rechazado y SyntaxError como en el título.
¿Es posible que el formato sin procesar del archivo esté causando este error? Si es así, ¿cómo prevenirlo?
Están pasando algunas cosas.
JSON.parse . Debe usar await o then para usar la respuesta:getProjects llama a response.json() que analizará el json. No es necesario analizarlo de nuevo.¿Qué hay de usar:
let rawFile = await this.getProjects("https://gitlab.example.com/api/v4/projects/1/repository/files/readme%2Emd/raw?ref=master", "GET") Si la respuesta es json , eso le daría un objeto, pero si la respuesta no es json, querrá usar response.text() en su lugar. Necesitarías una función diferente:
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() }entonces llámalo así:
let rawFile = await this.getTextFile("https://gitlab.example.com/api/v4/projects/1/repository/files/readme%2Emd/raw?ref=master")