Create companies using XMLHttpRequest returning 400 Error


#1

I am attempting to create a company using the api, but I am getting a 400 error. Followed the api docs for expected params, so not sure why it is deemed a bad request.

var url='https://api.hubapi.com/companies/v2/companies?hapikey=';
var params = '{"properties": [{"name": "name","value": "OK Company"}, {"name": "description","value": "Ok company" }]}';
var xhr = new XMLHttpRequest();
var json = JSON.stringify(params);
alert(json);

xhr.open("POST", url, true);
xhr.setRequestHeader('Content-type','application/json');
xhr.onload = function () {
if (xhr.readyState == 4 && xhr.status == "200") {
alert("SUCCESS");
} else {
alert(json + "FAILED");
}
}
xhr.send(json);


#2

Hi @clevy,

Are you trying to make this request client-side? The HubSpot APIs don't support support cross-origin (CORS) AJAX requests. Making the request client-side using JavaScript would expose any authentication you're using for the request. In order to use JavaScript/AJAX, you'll need to make the request (excluding any authentication) to an external server that could then add the needed authentication and make requests to HubSpot's APIs server-side.


#3

Thanks for responding @Derek_Gervais. I am aware of the CORS limitation, and I am working around it for testing, also using the test portal, when the application is live, I will make the request on an external server.

I solved my issue in case anyone else runs into it. The script was escaping my param arguments and which was causing a malformed json.

Changed stringify to no longer escape my braces.