I'm currently developing a Next.js React app with TypeScript and I am wondering if I need a server to make requests to the GitHub API. In my next.config.mjs file, as shown below, the only task my app needs is to fetch content from a file in a public repo on GitHub.
const nextConfig = {
async headers() {
return [
{
source: "/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "*" },
{ key: "Access-Control-Allow-Methods", value: "GET,DELETE,PATCH,POST,PUT" },
{ key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
]
}
]
}
}
Here's the code snippet for the API call:
useEffect(() => {
const fetchCode = async () => {
const response = await fetch(`https://api.github.com/repos/Kanav-Arora/DSA-Guide/contents/Binary Search/binary_search.cpp`, {
headers: {
Authorization: `Bearer ${github_api}`,
},
method: 'get',
mode: 'cors',
});
console.log(response);
}
fetchCode();
}, [cpp])
The error received is:
Response {type: 'cors', url: 'https://api.github.com/repos/Kanav-Arora/DSA-Guide/contents/Binary%20Search/binary_search.cpp', redirected: false, status: 401, ok: false, …}
I have attempted to configure CORS settings but the GitHub API still does not work in the development environment, even though it functions correctly in Postman.