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!!!

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