1

Hi Have a below code in apex

Http http = new Http();
HttpRequest request = new HttpRequest();
string accessToken;
request.setEndpoint(URL);
request.setMethod('POST');
HttpResponse response = http.send(request);
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200) {
    Map<String, Object> results = (Map<String, Object>) 
    JSON.deserializeUntyped(response.getBody());
    accessToken = (string)results.get('access_token');
}

Now whatever the response body received from this, needs to be iterated on the LWC page so I made the above method as auraEnabled and calling it on JS and it is working perfactly fine but instead, I am trying to skip the apex part and wants to call out on LWC page itself so to do the same I wrote below JS code.

JS code:

 fetch(endPoint, {
    method: "POST"
})
.then((response) => response.json())
/* response.json() gives us back a promise
we need to process the promise in .then()*/
.then((repos) => {
    console.log(repos);

});

and also I have added the endpoint under CSP trusted sites and remote site settings of course.

enter image description here

enter image description here

and checked all the boxes

I am getting the below error

Access to fetch at 'myendpointhere' from origin 'https://mydomain.lightning.force.com' has been blocked by CORS policy: 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.

Can anyone please help me to resolve this issue

2

1 Answer 1

1

try using mode: "no-cors".

const accessToken = 'super-secret-access-token-here'

fetch(endPoint, {
  method: 'GET',
  mode: 'no-cors',
  headers: {
    Authorization: `Bearer ${accessToken}`
  }
})

also don't forget to pass in the Authorization token you were using in Apex (I assume you still need it).

3
  • Actually, I am getting the error when making a first post call to get the access token
    – gs650x
    Jun 9, 2021 at 8:04
  • sorry for posting the get request, I have updated my question with the post request I am making to get the access token
    – gs650x
    Jun 9, 2021 at 8:06
  • should work the same whether its a GET or POST request, the main point there is adding mode: "no-cors" which should bypass the CORS issues.
    – lu_ke____
    Jun 11, 2021 at 1:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .