Hello,
I am still new to all of this.
I am working through HubSpot’s walkthrough, “Getting Started With Serverless Functions,” and ran into a CORS error. This is the walkthrough: Get started with serverless functions - HubSpot docs . Could it be that I am using a domain name for the site?
The error:
Access to fetch at ‘url’ from origin ‘url’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
The urls have been removed from above but were in the original.
Congratulation.js:
exports.main = (context, sendResponse) => {
// your code called when the function is executed
const functionResponse = "Congrats! You've just deployed a Serverless Function.";
const headers = {
'Access-Control-Allow-Origin': '*', // allows access from any domain
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
};
if (context.request.method === 'OPTIONS') {
// preflight request. reply successfully:
sendResponse({
statusCode: 200,
headers: headers,
});
return;
}
// actual request; reply with the actual function response:
sendResponse({
body: functionResponse,
statusCode: 200,
headers: headers,
});
};
serverless.json:
{
"runtime": "nodejs18.x",
"version": "1.0",
"endpoints": {
"congratulation": {
"method": "GET",
"file": "congratulation.js"
}
}
}
test-function.html:
<!--
templateType: page
label: Page template
isAvailableForNewContent: true
-->
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>{{ content.html_title }}</title>
<meta name="description" content="{{ content.meta_description }}">
{{ standard_header_includes }}
<script>var requestOptions = {
'method': 'GET',
'headers': {
'Content-Type': 'application/json',
}
};
fetch("https://www.domainname.com/_hcms/api/congratulation", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
</script>
</head>
<body>
{% module "page_template_logo" path="@hubspot/logo" label="Logo" %}
{% module "page_template_rich_text" path="@hubspot/rich_text" label="Rich Text" %}
{{ standard_footer_includes }}
</body>
</html>
You can see one of my attempts to fix this issue. I also tried the cors express js library. Not sure what else to do. Could this be an issue with Cloudflare?
The response headers don’t even show the Access-Control-Allow-Origin. Do you think it may have to do with Cloudflare’s CORS settings?
Thank you