Getting CORS issue while accessing(only GET) third party API from AXIOS in SPFX react webpart

Amol Tidke 1 Reputation point
2020-10-28T13:01:40.317+00:00

Hi Friends,

I am getting below error when I make get call to third party API from AXIOS in my SPFX react webpart.

Access to XMLHttpRequest at 'API URL ' from origin 'SP online site workbench URL' 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.

my code blog:

let config = {
headers: {'Access-Control-Allow-Origin': '*'},
params: {
ts: current_time,
portal: abc
}
}

const response = await axios.get(APIUrl, config);

Initially I didn't pass Access-Control-Allow-Origin in headers but now I passed and check but getting the same issue.

All reply will be appreciated.

Thank you.

SharePoint Server Development
SharePoint Server Development
SharePoint Server: A family of Microsoft on-premises document management and storage systems.Development: The process of researching, productizing, and refining new or existing technologies.
1,569 questions
{count} votes

2 answers

Sort by: Most helpful
  1. sadomovalex 3,626 Reputation points
    2020-10-28T15:34:46.767+00:00

    can you use SPHttpClient instead of axios object like shown here: Getting around CORS issues in SPFx with SPHttpClient. If config params which are passed to axios.get() method are translated to query string in HTTP GET request it should be possible.

    0 comments No comments

  2. Jerryzy 10,561 Reputation points
    2020-10-29T08:56:25.573+00:00

    Hi @Amol Tidke ,

    Please use SPHttpClient to overcome CORS issue:

    Getting around CORS issues in SPFx with SPHttpClient

    private async postToChannel(msg = "Testing API", channel = this.channel) {  
          const url = `https://slack.com/api/chat.postMessage?token=${  
              this.token  
          }&channel=${this.channel}&text=${msg + " using HttpClient"}`;  
      
      
        return await this.context.httpClient.post(  
            url,  
            HttpClient.configurations.v1,  
            {  
              mode:"cors",  
              headers:{  
                "Content-Type":"application/x-www-form-urlencoded"  
              }  
            }  
        );  
    }  
    

    Here is a similiar issue posted in GitHub for your reference:

    Problem making 3rd party API calls using SPFx


    If an Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments