Accessing third party API without CORS error in SPFx using Azure Function

When we access third-party API in the SPFx web part, sometimes we will get a CORS error, we can fix this issue using a simple azure function.

CORS Error

Access to fetch at 'https://api.darksky.net/forecast/febb2871126cd24613f32a79c32d4158/1.222,2.333' from origin 'https://ravichandran.sharepoint.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.

Create a new Azure function and go-to CORS page and select the “Enable Access-Control-Allow-Credentials” check box, paste your SharePoint tenant URL without forwarding slash and the end (ex, https://tenant.sharepoint.com/) in the “Allowed Origin” section and save

Go to the Function page and select “Create” select HTTP trigger template and after getting created go to “code + Test” and paste the following code. Save and get the function URL 

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    string name = req.Query["name"];
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    var client = new HttpClient();
    var response = await client.GetAsync("https://api.darksky.net/forecast/febb2871126cd24613f32a79c32d4158/1.222,2.333");
    var content = await response.Content.ReadAsStringAsync();
    return new OkObjectResult(content);
}

In the SPFx web part call the Azure function URL

import { HttpClient } from '@microsoft/sp-http';

export default class SpfxCors extends React.Component<ISpfxCorsProps, {}> {
  constructor(props: ISpfxCorsProps) {
    super(props);
    this._getFeeds();
  }

  private async _getFeeds() {
    let response = await this.props.context.httpClient.get("https://kljdlkf87.azurewebsites.net/api/HttpTrigger1?code=XgdKg2k5zMRaOumro5Gv16uz81I1fp0yZyyUpiPES7cYHtskjgavMQ==", HttpClient.configurations.v1);
    console.log(response);
    console.log("REST API response received.");
    let tasks = await response.json();
    console.log(tasks);

  }

If you have any questions, feel free to let me know in the comments section.
Happy coding!!!

3 thoughts on “Accessing third party API without CORS error in SPFx using Azure Function

  1. Navaratan Sharma November 12, 2021 / 11:29 am

    i tried code which you provided. but it is gives following error message.

    TypeError: Failed to fetch
    at FetchProvider.UE6e.FetchProvider.fetch (sp-webpart-workbench-assembly_en-us.js:49867)
    at Function.8Y7G.HttpClientHelper.fetchCore (sp-webpart-workbench-assembly_en-us.js:48803)
    at HttpClient.LJZb.HttpClient._fetch (sp-webpart-workbench-assembly_en-us.js:49488)
    at HttpClient.LJZb.HttpClient.fetch (sp-webpart-workbench-assembly_en-us.js:49456)
    at HttpClient.LJZb.HttpClient.get (sp-webpart-workbench-assembly_en-us.js:49469)
    at SpfxCors. (SpfxCors.tsx:58)
    at step (SpfxCors.module.scss.ts:17)
    at Object.next (SpfxCors.module.scss.ts:17)
    at SpfxCors.module.scss.ts:17
    at new Promise ()

    but following code is working for same URL

    let reqUrl = “https://api.darksky.net/forecast/fe01c49b6533f1d7460ed2e82302b5bc/24.4851589,74.8916458?callback=?&units=si”;
    $.getJSON(reqUrl, (data) => {
    console.log(“data :”);
    console.error(data);
    }).catch((jqXHR, textStatus, errorThrown) => {
    console.error(textStatus);
    console.log(textStatus);
    });

    thanks
    navaratan

    Like

  2. Ravichandran Krishnasamy November 12, 2021 / 11:34 am

    You have to use the azure function, I’ll make the video for this and post it this weekend for your better understanding

    Like

    • navaratan November 14, 2021 / 4:04 pm

      thanks ravichandra

      Like

Comments

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s