I am creating a part of a website where the user can design a certain picture. When they are done I want the picture to be sent to a company Google Drive. I do not have access to the backend of that website, therefore I need to make all this work just in JavaScript.
I set up the API key and OAuth in Google Developer Console. However, I can't find a good solution to make the authentication work. The gapi.auth.getToken() always returns 404. My code looks like this:
function initClient() {
gapi.client
.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
scope: "https://www.googleapis.com/auth/drive",
discoveryDocs: [
"'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'",
],
})
.then(function () {
GoogleAuth = gapi.auth2.getAuthInstance();
GoogleAuth.isSignedIn.listen(updateSigninStatus);
});
}
function sendToDrive() {
gapi.load("client:auth2", initClient);
let file = canvas.toDataURL("image/png"); // file
var metadata = {
name: file.name,
mimeType: file.type,
parents: [FOLDER_ID],
};
var form = new FormData();
form.append(
"metadata",
new Blob([JSON.stringify(metadata)], { type: "application/json" })
);
form.append("file", file);
fetch(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
{
method: "POST",
headers: new Headers({
Authorization: "Bearer " + gapi.auth.getToken().access_token, // Returns 404
}),
body: form,
}
)
.then((res) => {
return res.json();
})
.then(function (val) {
console.log(val);
});
}
Not sure where to look now - the OAuth and API Key configuration seems right, the code returns 404 with no explanation ("gapi.client.error: Pa"), and I couldn't find this kind of use case in the docs (backend side is always used there).
Thanks in advance for any help!