How do you return a function from an express server and run it in a browser?
I have hosted a function on Google Cloud Platform (Cloud Functions) and want to run it in a web application via a script tag. The function is in Nodejs 16 and can be called via https, and is a simple hello world example:
exports.helloWorld = () => {
const widget = console.log("This is a widget");
return widget();
}
However, it seems as though I cannot call it that way, because I get an Error: could not handle the request and a 500 status message each time I try to hit the endpoint.
I want to be able to embed this function on a website via something like:
<script src="https://example.com/function-name"/>
How can I achieve that?
It seems that your Cloud Function is malformed. When you create a Cloud Function you have to return a status code otherwise the Cloud Function will timeout waiting for the return status code (throwing the 500 error you had).
If I guess correctly what you want to do is call an external script from the Cloud Function, you can use the next code:
exports.helloWorld = (req, res) => {
let message = 'alert("Hello world from CF")'; //Or any js code script here
res.status(200).send(message);
};
And call it from the HTML page like this:
<!DOCTYPE html>
<html>
<head>
<script src="https://zone-project-id.cloudfunctions.net/helloworld"></script>
</head>
<body>
<!-- the content goes here -->
Hello world!
</body>
</html>