October 23, 2024
Chicago 12, Melborne City, USA
javascript

Axios throws Error 400 while trying to make get request in typescript


while trying to call a github raw url using axios get request in typescript i am getting error 400.
the same link when being tried with python script and curl command gives response 200.
I tried adding headers in axios request but it did not helped.

Attaching the code below,

import axios, { AxiosRequestConfig } from 'axios';

async function fetchGitHubRawFile(owner: string, repo: string, branch: string, path: string): Promise<string> {
    const encodedPath = encodeURIComponent(path); // Encode the path
    const url = `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/${encodedPath}`;
    console.log('Fetching URL:', url); // Debugging log
    const config: AxiosRequestConfig = {
        headers: {
            'Content-Type': 'text/plain; charset=utf-8', 
            'Accept': 'application/text',
            'Access-Control-Allow-Origin': '*', 
            'Cross-Origin-Resource-Policy': 'cross-origin',
            'X-XSS-Protection': '1; mode=block',
            'Content-Encoding': 'gzip', 
            'Accept-Ranges': 'bytes',
        }
    }
    try {
        const response = await axios.get(url, config);
        return response.data;
    } catch (error) {
        if (axios.isAxiosError(error)) {
            console.error('response headers:', error.response?.headers);
            console.error('Axios error:', error.message);
            console.error('Response data:', error.response?.data); // More detailed error info
        } else {
            console.error('Unexpected error:', error);
        }
        throw error;
    }
}
//https://raw.githubusercontent.com/tensorflow/tensorflow/master/README.md
const owner="tensorflow"; 
const repo = 'tensorflow'; 
const branch="master"; 
const filePath="README.md"; 
fetchGitHubRawFile(owner, repo, branch, filePath)
    .then(data => {
        console.log('File content:', data);
    })
    .catch(error => {
        console.error('Failed to fetch file:', error);
    });

what could be this issue and how to resolve this?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video