javascript - Error fetching repositories: HTTP error! status: 401 - Stack Overflow

admin2025-05-01  0

So, I developed a portfolio website that fetches repositories and details from GitHub and send it to my website. While using localhost everything was working fine but as i deployed the code in Vercel it is showing ERROR 401

Function to get repositories from the GitHub API using Bearer key authentication:

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 = `/${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' });
  }
};

Function to send the repositories in the frontend:

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();

Code to start the server:

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}`);
});

So, I developed a portfolio website that fetches repositories and details from GitHub and send it to my website. While using localhost everything was working fine but as i deployed the code in Vercel it is showing ERROR 401

Function to get repositories from the GitHub API using Bearer key authentication:

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' });
  }
};

Function to send the repositories in the frontend:

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();

Code to start the server:

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}`);
});
Share Improve this question edited Jan 20 at 22:48 Laurent FAVOLE 4071 gold badge4 silver badges15 bronze badges asked Jan 2 at 19:04 Anik DasAnik Das 291 silver badge1 bronze badge 1
  • 2 Please tell us more about the error you're getting. Is it your HTML page that emits the ERROR 401, or the axios.get()? Always copy the complete and exact error message in your question. When a line number is mentioned point out which line that is. Remember that people cannot actually run your code, so all they can do is read it and try to make sense of the error message. – KIKO Software Commented Jan 2 at 19:07
Add a comment  | 

1 Answer 1

Reset to default 2

I think you problem is located in the Authorization Header.

The header should look like this:

    Authorization: Bearer YOUR-TOKEN

And yours looks like this:

    Authorization: `token ${GITHUB_TOKEN}` 

So you just need to change it to this:

    Authorization: `Bearer ${GITHUB_TOKEN}`

I am using this doc to see what is expected from github: https://docs.github.com/en/rest/authentication/authenticating-to-the-rest-api?apiVersion=2022-11-28

转载请注明原文地址:http://anycun.com/QandA/1746101636a91689.html