I’ve been trying to update a file to my GitHub repository through my code to create an automated system that pushes changes automatically. I tried creating a function that ‘adds’ a file using a GitHub access token, and tried to get the repo and push to it. Then in my HTML file, I have a button that runs this function through an onclick event. Here is what I tried:
function upload() {
return fetch(
`https://api.github.com/repos/MY-USERNAME/MY-REPO-NAME/contents/amogus.html`,
{
method: "PUT",
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer {MY ACCESS TOKEN HERE}`
},
body: JSON.stringify({
message: "amogus",
content: "aaaaa"
})
}
).then((res) => res.json());
}
EDIT
I figured it out. Apparently, GitHub only supports Bse64 encoded files, so you only have to convert your file data TO Base64 using the following code:
content: btoa("your text here")
This converts your file content to Base64, which can be uploaded to GitHub.
This unfortunately does not do anything to the repo and does not return any errors. Am I doing anything wrong? Thank you.
2
Answers
Solution
Apparently, GitHub only supports Bse64 encoded files, so you only have to convert your file data TO Base64 using the following code:
content: btoa("your text here")
btoa(string)
converts a string to Base64, which can be uploaded to GitHub.It’s a good start. I would think about adding error handling and making it more async to understand the workflow:
Error Handling:
Currently, the code does not include error handling for the HTTP request. It’s important to handle potential errors and provide appropriate feedback to the user. You can use a try…catch block to catch any errors that occur during the API request and handle them accordingly.
Asynchronous Function:
Convert the upload() function to an asynchronous function by using the async keyword. This allows you to use await within the function, making the code more readable and easier to work with.
Separation of Concerns:
It’s generally a good practice to separate your JavaScript logic from your HTML code. Instead of using an onclick event directly in your HTML, consider adding an event listener in your JavaScript code. This helps to keep your code organized and maintainable