最近调用gitLab的api去获取文件内容时,总报错

调用的是这个api

https://<仓库地址>/api/v4/projects/<仓库ID>/repository/files/<文件路径>?ref=<分支>

//调gitLab api时,请求头记得设置token,还要禁用ssl验证

const agent = new https.Agent({  
  rejectUnauthorized: false  // 禁用SSL验证
});
const res = fetch(api,{
  headers:{
    "PRIVATE-TOKEN": `${GITLAB_PERSONAL_ACCESS_TOKEN}`
  },
  agent
})

但总是报错404

于是在导师的帮助下,换了一种实现方式,成功获得指定路径的内容

1.先通过tree api获得指定路径的目录,这个api会返回一个数组,里面存储了该路径包含的所有文件的ID,名称,类型,路径,我们主要为了拿到ID

https://<仓库地址>/api/v4/projects/<仓库ID>/repository/tree?path=<文件路径>&ref=<分支>
[
  {"id":"***",
   "name":"demo",
   "type":"tree",//这是个文件夹
   "path":"src/app/modules/component-help/component/button/demo",
   "mode":"***"
  },
  {"id":"***",
   "name":"button-help.component.html",
   "type":"blob",//这是个文件
   "path":"src/app/modules/component-help/component/button/button-help.component.html",
   "mode":"***"
  },
  ...
]

2.拿到ID后再调用另一个api,获取内容

https://仓库地址/api/v4/projects/<仓库ID>/repository/blobs/<文件id>/raw?ref=<分支名称> 

这样就可以成功获取想要的文件内容啦

至于files api为什么报错,我仍然不知道,如果有朋友知道的话,欢迎在评论区解惑

Logo

加入社区!打开量化的大门,首批课程上线啦!

更多推荐