拉取Gitlab仓库raw文件出现JSON解析SyntaxError如何解决
问题原因说明
- 这个报错不是Gitlab raw文件格式直接导致的,是代码存在两处逻辑错误触发的:
- 封装的
getProjects方法对所有请求都统一调用response.json()解析返回值,但Gitlab raw文件接口返回的是纯文本内容(比如示例中README.md的markdown内容),不是标准JSON结构,response.json()本身就会抛出JSON解析失败的异常。 - 调用
getProjects拉取raw文件时漏写await关键字,直接把返回的Promise对象传给JSON.parse解析,相当于尝试把Promise的字符串形式转成JSON,自然会报格式错误。同时catch分支里直接把请求方法的返回值赋值给变量,没加await拿到的永远是Promise对象,自然会打印处于rejected状态的Promise。
- 封装的
修复方案
第一步:改造通用请求方法,支持不同响应类型解析
调整请求封装逻辑,支持指定响应解析格式,避免所有响应都强制转JSON:
async request(url, method, payload, responseType = 'json') { const token = this.$store.getters.token const headers = { 'Content-Type': 'application/json', 'Private-Token': token } // GET请求不需要传body const options = { method, headers } if (method.toUpperCase() !== 'GET' && payload) { options.body = JSON.stringify(payload) } const response = await fetch(url, options) // 根据指定类型解析响应 if (responseType === 'text') { return response.text() } return response.json() }
第二步:调整raw文件拉取逻辑
调用拉取raw文件接口时指定响应类型为text,同时补全await关键字:
async addNewProject() { // 创建项目逻辑调整为await写法更易维护 try { const createRes = await this.request("https://gitlab.example.com/api/v4/projects/", "POST", { "name": "newProjectName", "namespace_id": 12, "description": "description" }) console.log(createRes.id) } catch (e) { console.error('创建项目失败', e) } let rawFile = null try { // 拉取raw文件指定响应格式为text,补全await关键字 rawFile = await this.request("https://gitlab.example.com/api/v4/projects/1/repository/files/readme%2Emd/raw?ref=master", "GET", null, 'text') } catch (e) { console.error('拉取raw文件失败', e) rawFile = '文件读取失败' } console.log(rawFile) // 此时输出就是README.md的纯文本内容 }
内容的提问来源于stack exchange,提问作者AbreQueVoy
相关产品推荐
相关产品推荐

