CORS error when trying to get access token in Javascript using Axios and/or Fetch

Hello,
I am trying to get an access token using Javascript.
I have visited the authorization URL (https://cloud.lightspeedapp.com/oauth/authorize.php?response_type=code&client_id={CLIENT_ID}&scope=employee:all) to get my token.
Now I am trying to send a request to get my access token but I get a CORS error:
Access to fetch at 'https://api.lightspeedapp.com/oauth/access_token.php' from origin 'https://{DOMAIN.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.
When using Postman everything is working fine, but when trying through Javascript, using fetch for example, I get the CORS error. My code is as follows:
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json', "Access-Control-Allow-Origin": "*" },
body: {
"client_id": "MY_ID",
"client_secret": "MY_SECRET",
"grant_type": "authorization_code",
"code": "MY_AUTH_CODE_FROM_URL"
}
};
fetch('https://api.lightspeedapp.com/oauth/access_token.php', requestOptions)
.then(response => console.log(response))
Does anyone know how I can solve this CORS error?
Thanks in advance,
Mike
6 comments
Hi @Mxkert,
Thank you for contacting us.
Maybe this post can help you https://community.lightspeedhq.com/en/discussion/985/access-control-cors-headers
Hi @LucienVersendaal,
It was indeed an error from my side, my JSON object wasn't structured correctly.
Thank you.
Hi @Mxkert,
Okay perfect that it's fixed now.
@LucienVersendaal
we are having this same issue with a json call in our print templates. we are trying to pull images based on code from 2019 and are getting the same blocked by CORS policy message. when everyone says that it may be on the app end, does that mean there are issues with the script in the print template, or is it lightspeeds database itself that is not allowing us to pull the json information.
Hi,
CORS policy is not an error what comes from Lightspeed. This is coming from your browser. You'll need to send the "Access-Control-Allow-Origin" in the header.
@LucienVersendaal
when dealing with print templates, how do I do that as the information is being pulled from api.lightspeedhq.com and the request is being made from us.merchantos.com? All of the other forum posts leads to having to make the JSON request from lightspeedhq.com. I am how sure how I adjust the info within lightspeedhq.com. When I change the .json url to come from us.merchantos.com to match the request origin it outputs nothing but no longer gives the CORS error.