Node.js调用Bitbucket API返回HTML而非JSON问题求助
修复Bitbucket提交记录API返回HTML的问题
你的问题出在三个关键地方:用了网页访问路径而非API端点、Accept头设置错误、响应处理方法不对,以下是修复方案:
使用正确的Bitbucket REST API端点
你当前调用的是Bitbucket的网页前端URL,它默认返回HTML页面。需要改用官方API路径,Bitbucket Server/Data Center的V1 API端点格式为:https://bitbucketexample.com/rest/api/1.0/projects/CD/repos/central-msp-config/commits设置正确的Accept请求头
你设置的是application/xml,但期望JSON响应,所以要把Accept头改成application/json。修正响应处理逻辑
node-fetch中,获取JSON响应应该用response.json()方法,而不是data.body()(这是获取可读流,需要额外处理)。
修正后的代码:
import fetch from 'node-fetch'; async function fetchCommits() { try { const response = await fetch('https://bitbucketexample.com/rest/api/1.0/projects/CD/repos/central-msp-config/commits', { method: 'GET', headers: { 'Accept': 'application/json', 'Authorization': 'Bearer YXIxMjAwOldlbGNvbWUxMDkqCg==' } }); console.log('响应状态码:', response.status); if (!response.ok) { throw new Error(`请求失败: ${response.statusText}`); } const commits = await response.json(); console.log('提交记录:', commits); } catch (error) { console.error('错误:', error.message); } } fetchCommits();
额外注意事项:
- 确认你的Bearer令牌有该仓库的读取权限,令牌无效或权限不足也可能导致跳转至登录页面(返回HTML)。
- 如果是Bitbucket Cloud(而非Server/Data Center),API端点格式不同,需要改用
https://api.bitbucket.org/2.0/repositories/{workspace}/{repo-slug}/commits,并且授权方式可能需要用Basic Auth或App Password。
内容的提问来源于stack exchange,提问作者Abilash Krishnan
相关产品推荐
相关产品推荐

