Skip to content

Instantly share code, notes, and snippets.

@bretmcg
Last active November 22, 2023 02:41
Show Gist options
  • Save bretmcg/edf0e80a1c600de6c2d40c973de55fc3 to your computer and use it in GitHub Desktop.
Save bretmcg/edf0e80a1c600de6c2d40c973de55fc3 to your computer and use it in GitHub Desktop.
Call Google Cloud Functions from HTML / Browser
#!/bin/bash
# 1. After deploy, update the function URL in index.html
# 2. If you rename myCloudFunction, change it here, index.js and index.html
# 3. The HTML file must be served from a server
# (or locally via something like $ python3 -m http.server)
gcloud functions deploy myCloudFunction \
--gen2 \
--runtime=nodejs20 \
--region=us-central1 \
--source=. \
--trigger-http \
--allow-unauthenticated
<!doctype html>
<html lang="en">
<head>
<script>
// TODO: update this URL to your Cloud Function URL. It should be in the
// format: https://us-central1-YOURPROJECTID.cloudfunctions.net/myCloudFunction';
const FUNCTION_URL = '*******CLOUD FUNCTION URL HERE*******';
</script>
<meta charset="utf-8">
<title>Calling a Google Cloud Function from HTML</title>
</head>
<body>
<input type="button" value="Click" onclick="callCloudFunction();" />
<input type="text" id="txt" value="Bret" />
<div id="output"></div>
<script>
async function callCloudFunction() {
let objToSend = {
name: document.getElementById('txt').value,
location: "NYC"
};
const responseRaw = await fetch(FUNCTION_URL, {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(objToSend)
});
const response = await responseRaw.json();
document.getElementById('output').innerText = `${response.greeting} ${response.name}`;
}
</script>
</body>
</html>
const functions = require('@google-cloud/functions-framework');
/*
A Google Cloud Function that is callable from an HTML page.
Responds to CORS preflight permissions check that uses the
OPTIONS method.
*/
functions.http('myCloudFunction', (req, res) => {
res.set('Access-Control-Allow-Origin', '*');
// Preflight OPTIONS request
if (req.method === 'OPTIONS') {
res.set('Access-Control-Allow-Methods', 'GET');
res.set('Access-Control-Allow-Headers', 'Content-Type');
res.set('Access-Control-Max-Age', '3600');
res.status(204).send('');
return;
}
// Normal request (GET, POST, etc)
const name = req?.body?.name ?? 'Bret';
let returnValue = {
name: name,
greeting: "Hello"
};
res.status(200).json(returnValue);
});
{
"dependencies": {
"@google-cloud/functions-framework": "^3.3.0"
}
}
@eternalparquet
Copy link

doesn't work

@bretmcg
Copy link
Author

bretmcg commented Nov 22, 2023

@eternalparquet I updated the example to use gen2 of Cloud Functions, so it should be working now. Thanks for the bug report!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment