How to fix cors is not allowing API request issue

I’m using hubspot create contact API.
My front end is react JS application.
I have added my domain in Additional site domains as well.
But still I’m facing CORS issue while POST API request.
Anything else do I need to do for CORS issue ?

@piersg , @tjoyce -- either of you folks able to help out here :grinning_face:

Hi @AKinwad ,
We have to use serverless function for this cors error. Please followed serverless documentation with using node js.
Docs : Get started with serverless functions - HubSpot docs
Example code of serverless for how to get deal using serverless function :
// Require axios to make API requests in the function
const axios = require(“axios”);
const request = require(“request”);
exports.main = (body, sendResponse) => {
const HAPI_KEY = ‘demo’;
const vid = body.params.vid[0];
let req = {
“properties”: [ “event_id”, “courses_ids” ],
“filterGroups”:[
{
“filters”:[
{
“propertyName”: “associations.contact”,
“operator”: “EQ”,
“value”: vid
}
]
}
]
};
axios
.post('https://api.hubapi.com/crm/v3/objects/deals/search?hapikey='+HAPI_KEY,req)
.then(function(response) {
if(response.status == 200 && response.statusText == ‘OK’){
if(response.data.total > 0) {
array = response.data.results;
console.log(array);
}
sendResponse({ body: response, statusCode: 200 });
}
})
};

Hope this helps!

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

Hello @webdew
Thank you fior your response.
However, I tried editing my POST api call as your above example but still getting CORS issue.
Let me know if you need more info from my side.
Im using versel to deploy my frontity react application.
Im using frontity in my react application.

Hi @AKinwad,

You have required serverless function on creating option in design tools in hubspot.
If you are using react app then your actually domain and ajax url domain will be same then cors error not occur. firstly you send request to serverless function using ajax then call api using axios in node.js.
For created serverless function use below code :
Docs : Get started with serverless functions - HubSpot docs

Hope this helps!

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

@AKinwad - Please, do not post directly to the contacts API from the browser.

You need to create a function on a server that makes the request for you, this will allow you to obfuscate your API KEY. This is also the reason you are having CORS issues..

I personally use PHP but, you can use Node, Ruby, Python, etc…