因此,我开发了一个投资组合网站,该网站从 github 获取存储库和详细信息并将其发送到我的网站。使用 localhost 时一切正常,但当我在 vercel 中部署代码时,它显示错误 401
使用 Bearer key 身份验证从 github api 获取存储库的功能
const axios = require(axios);
const fetchrepositories = async (url,headers,retries = 3)=>{
try{
const response = await axios.get(url , {headers});
return response.data;
}catch(error){
if(retres.error > 3 && error.response?.status === 403){
console.warn(`Rate limit reached. Retrying in 60 seconds...`);
await new Promise(resolve => setTimeout(resolve, 60000)); // Wait 60 seconds
return fetchRepositories(url, headers, retries - 1);
}throw error;
}
};
module.exports = async (req, res) => {
const username = 'coderanik'; // Replace with the GitHub username
const apiUrl = `https://api.github.com/users/${username}/repos?sort=created&direction=desc`;
const GITHUB_TOKEN = process.env.GITHUB_TOKEN || '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';
try {
const response = await axios.get(apiUrl, {
headers: {
Authorization: `token ${GITHUB_TOKEN}` // Optional for higher rate limits
}
});
// Return only the top 6 repositories
const recentRepos = response.data.slice(0, 6);
res.status(200).json(recentRepos);
} catch (error) {
console.error('Error fetching repositories:', error.message);
res.status(error.response?.status || 500).json({ error: 'Failed to fetch repositories' });
}
};
前端发送存储库的功能
async function fetchRepositories() {
try {
const response = await fetch('/api/repositories'); // Calls the serverless function
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const repos = await response.json();
renderRepositories(repos);
} catch (error) {
document.getElementById('repositories').innerHTML = `<p>Error fetching repositories: ${error.message}</p>`;
console.error("Failed to fetch repositories:", error.message);
}
}
function renderRepositories(repos) {
const repoContainer = document.getElementById('repositories');
repoContainer.innerHTML = ''; // Clear the loading message
repos.forEach(repo => {
const repoElement = document.createElement('div');
repoElement.className = 'repo';
repoElement.innerHTML = `
<h3>${repo.name}</h3>
<p>Created At: ${new Date(repo.created_at).toLocaleString()}</p>
<p>Language: ${repo.language || 'Not specified'}</p>
<button onclick="window.open('${repo.html_url}', '_blank')">View on GitHub</button>
`;
repoContainer.appendChild(repoElement);
});
}
fetchRepositories();
启动服务器的代码
const express = require('express');
const path = require('path');
const app = express();
// Serve static files
app.use(express.static(path.join(__dirname, 'public')));
// API routes
app.use('/api/repositories', require('./api/repositories'));
// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
我认为您的问题位于授权标头中。
标题应如下所示:
Authorization: Bearer YOUR-TOKEN
你的看起来像这样:
Authorization: `token ${GITHUB_TOKEN}`
所以你只需要把它改成这样:
Authorization: `Bearer ${GITHUB_TOKEN}`
我正在使用此文档来查看 github 的预期内容: https://docs.github.com/en/rest/authentication/authentication-to-the-rest-api?apiVersion=2022-11-28