From a SP Online SPFx Web Part (No Javascript Framework), I've been trying to do a GET request to an API that expects some headers and nothing works.
If use Postman, with the same URL and Headers it does work.
first attempt :
    var _headers = {
      'Content-Type': "text/plain",
      'Authorization': "TOKENVALUE",
      'X-Requested-With': "HREngagement",
    };
    const myOptions: ISPHttpClientOptions = {
      headers: new Headers(_headers),
      credentials: 'same-origin',
      method: 'GET',
      mode: 'no-cors',
      redirect: 'follow'
    };
    this.context.spHttpClient.get(_url, SPHttpClient.configurations.v1, myOptions)
    .then((response: SPHttpClientResponse) => {
    console.log('OK!!!!');
      console.log(response.text);
      console.log('OK!!!!');
      return response;
    });
Error:
net::ERR_ABORTED 401 (Unauthorized)
OK!!!!
ƒ () { return this.nativeResponse.text(); }
OK!!!!
Second attempt :
return axios({
  method: 'get',
  url: _url ,
  headers: {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, OPTIONS',
  'Content-Type': "text/plain",
  'Authorization': "TOKENVALUE",
  'X-Requested-With': "HREngagement",
  },
  }).then(function(response){
  return response.data;
});
Nothing works for me, these are the errors I've been getting:
Error:
Access to XMLHttpRequest at 'url' from origin 'https://localhost:4321' 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.
Apparently consuming an external API from a SPFx Web Part it’s harder that one would imagine!
Is there any sample code for doing this?