Access to XMLHttpRequest blocked by CORS policy

Hi everyone,

I’m currently in the process of making a custom form module that essentially takes the input from the form on submit, and sends an API POST request using the input that the user has submitted.

The problem is that I keep getting the following error :

‘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.’

I want to know what the best solution to this problem could be? When I run the website on a chrome tab with disabled web security, it seems to work fine, but this doesn’t seem like a robust long-term solution.

I’m quite new with web dev and API integration so any suggestions would be greatly appreciated, thanks!

Hi @sdeveloper ,

Because, HubSpot supports same domain with ajax request only or IP allowlisted on third party api if you can otherwise use serverless function for that.

Hope this helps!

If we were able to answer your query, kindly help the community by marking it as a solution.
Thanks and Regards.

I add an API with following script in let’s say https://besttigwelders.com/

<script src=“http://apiendpoint.com/api/v1/api.js”></script>

<div id=“api” data-apikey=“LA59CJI9HZ-KIJK4I5-3CKJC”></div>
api.js

$(function () {

apikey = $(‘api’).data(‘apikey’);
$(“api”).load(“http://apiendpoint.com?apikey=” + apikey);

})
When I load the page, I get following error:

XMLHttpRequest cannot load apiendpoint URL. Redirect from ‘apiendpoint URL’ to ‘apiendpoint URL’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘test URL’ is therefore not allowed access.

In the path of apiendpoint.com I added in .htaccess following code:

Header set Access-Control-Allow-Origin “*”

Thanks for the response.

Do you know how I would edit/add the htaccess code for the website/module?

The form module doesn’t seem to have a .htaccess file (maybe I add one in the linked files section?), and the actual website using the form module I created using the HubSpot website page builder and I don’t see a way to add/edit a .htaccess file in there as well.

Hello @sdeveloper,

Try by adding the domain in Settings > Tracking & Analytics > Tracking code > Advanced tracking tab then add your domain in Additional site domains.

This post explains about CORS for your reference - https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-receive-a-no-access-control-allow-origin-header-i

Hope this helps!

Regards,

Thanks for the response.

The domain already seems to be in the additional site domain, so it doesn’t let me add the specific site..

Any other suggestions would be greatly appreciated.

Here is 100% working solution - for post data into hubspot form via creating JS API request -

<script charset=“utf-8” type=“text/javascript” src=“//js.hsforms.net/forms/v2.js”></script>
<script>
const hubspot_form_id = ‘{{ module.form_field.form_id }}’ ;
function submitForm() {
console.log(“test script”);
var hbFrameId = ‘hs-form-iframe-0’;
var hbFormId = ‘hsForm_’ + hubspot_form_id;
var btnClass = ‘hs-button primary’;

var myForm = document.getElementById(‘home-page-contact’);
// var iframe = document.getElementById(hbFrameId);
var frm = document.getElementById(hbFormId);
for(var i=0; i<frm.elements.length; i++){
var hbField = frm.elements[i];
for(var j=0; j<myForm.elements.length; j++){
var myField = myForm.elements[j];
if(myField.name == (“hb-”+hbField.name)){
hbField.value = myField.value;
}
}
}
var dataJson = $(frm).serializeArray();
var data = new FormData($(frm)[0]);
$(frm).submit();
}

hbspt.forms.create({
portalId: “16252”,
formId: hubspot_form_id,
onFormReady: function () {
document.getElementsByClassName(‘hbspt-form’)[0].style.display = ‘none’;
},
});

</script>

Contact Any API Integration Or For Hubspot realted Query Crowdvolley PVT LTD.

Saurabh Upadhyay

Hi Supadhyay,

Thanks for sharing your solution. I tweakid it a little bit because the javascript didn’t saw the iframe:

function submitForm() {
console.log(“test script”);
var hbFrameId = ‘hs-form-iframe-0’;
var hbFormId = ‘hsForm_’ + hubspot_form_id;
var btnClass = ‘hs-button primary’;

var frm = [];
var myForm = document.getElementById(hbFrameId).contentWindow.document.getElementById(hbFormId);
var iframe = document.getElementById(hbFrameId);
var frm = document.getElementById(hbFrameId).contentWindow.document.getElementById(hbFormId);
console.log(frm);
console.log(frm.elements[0]);
frm.elements[0].value = “{{profile.email}}”;
const elem = frm.elements.length;
console.log(frm.elements[0]);
for(var i=0; i < elem; i++){
var hbField = frm.elements[i];
for(var j=0; j < elem; j++){
var myField = myForm.elements[j];
if(myField.name == (“hb-”+hbField.name)){
hbField.value = myField.value;
}
}
}
var dataJson = $(frm).serializeArray();
var data = new FormData($(frm)[0]);
$(frm).submit();
}

I am having the same error with this code

<!--
templateType: “section”
label: “Multi-row content”
isAvailableForNewContent: true
-->

{% dnd_section %}

{% dnd_module path=‘@hubspot/rich_text’ %}
{% module_attribute “html” %}
<div class=“newsletter”>
<div class=“container px-5 w-75”>
<div class=“row py-5”>
<div class=“col-12 col-md-6”>
<h3 class=“fw-bold”>:love_letter: Subscribe to my newsletter</h3>
<h5 class=“fs-6”>Subscribe to my newsletter, with thoughts on life, identity, making things and more.</h5>
</div>
<div class=“col-12 col-md-6 d-flex justify-content-md-end align-items-start”>
<form id=“newsletter” class=“w-100 w-md-auto”>
<input type=“text” class=“form-control mb-3 py-2” name=“firstName” placeholder=“First Name” required>
<input type=“email” class=“form-control mb-3 py-2” name=“email” placeholder=“Email address” required>
<button type=“submit” class=“btn btn-primary w-100 py-3”>Subscribe</button>
</form>
</div>
</div>
</div>
</div>
<script>

const url = ‘http://144585255.hs-sites-eu1.com/’;
const apiKey = ‘CiRldTEtMDg5YS1kYzI4LTRlNDktYjE1Ni01MWQ5N2IxODRhOGYQp-T4RBjYyNwfKhkABeaRgmYgcKaY6G_KnGDnM3HmvwmZv6eESgNldTE’;

const form = document.getElementById(‘newsletter’);

form.addEventListener(‘submit’, handleSubmit);

async function handleSubmit(event) {

event.preventDefault();

const formData = new FormData(form);
const data = Object.fromEntries(formData);

try {

const response = await fetch(url, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
‘Authorization’: `Bearer ${apiKey}`
},
body: JSON.stringify(data)
});

if(!response.ok) {
throw new Error(‘Request failed’);
}

alert(‘Subscription successful!’);
form.reset();

} catch (error) {
alert(‘Subscription failed. Please try again.’);
}

}

</script>
{% end_module_attribute %}
{% end_dnd_module %}
{% end_dnd_section %}
Access to fetch at ‘https://144585255.hs-sites-eu1.com/’ from origin ‘https://144585255.hubspotpreview-eu1.com’ 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.