1

I'm trying to execute query using REST API, in a lightning web component. the request in Postman returning result with success (enabling Follow Authorization header) but in the JavaScript in lightning web component it returns 401 Unauthorized the code in the java script is a follow :

let sessionId = 'tokken';
let baseUrl = window.location.origin;
let header = {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Authorization": "Bearer " + sessionId,
};
if (sessionId) {
    let options = {
        method: "GET",
        mode: 'no-cors',
        redirect: 'follow',
        headers: header,
    };
    fetch(baseUrl + '/services/data/v50.0/query/?q=SELECT+name+from+Account', options).then((response) => {
        console.log(JSON.stringify(response));
        if (!response.ok) {
            // throw Error(JSON.stringify(response));
        } else {
            return response.json();
        }
    }).then((repos) => {
        console.log(repos, repos);
    });
}

am I missing something ?

2 Answers2

1

Since you can not pass the value Authorization to no-cors mode, you will need to add CORS configuration in your SalesForce as safe endpoint where they let you make a call.

Giorgi Gvimradze
  • 1,714
  • 1
  • 17
  • 34
0

You can not send Authorization header with "no-cors" mode.

mode: "no-cors"only allows a limited set of headers in the request:

Accept
Accept-Language
Content-Language
Content-Type with a value of application/x-www-form-urlencoded, multipart/form-data, or text/plain
  • so what I should change to be able to send the authorization ? what mode should I put ? – Oubayda Samrouth Jan 10 '21 at 12:04
  • Just delete this line. It'll be use default mode which is "cors" mode. If you get cors error use [this extensions](https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf/related?hl=en) for fix it. – Eyup Ucmaz Jan 10 '21 at 20:03
  • Okay thanks for the help, but the client also have to install this extension to make this request work form him, right ? – Oubayda Samrouth Jan 11 '21 at 16:54