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

PnP Location Picker Control for SPFx

This location picker control allows you to search and select the location, also allows enter a custom location. also it is easy to use we don’t have to configure for API permissions

Importing location picker control

import { LocationPicker, ILocationPickerItem } from "@pnp/spfx-controls-react/lib/LocationPicker";

Control tag and the attributes

  <LocationPicker
          context={this.props.context}
          label="Location"
          defaultValue={this.state.selectedAddress}
          onChange={(locValue: ILocationPickerItem) => {
            this.setState({ selectedAddress: locValue })
          }
          } />

retrieve value from SharePoint list and assign value to the location picker control

  _getListItem = async () => {
    const item: any = await sp.web.lists.getByTitle("Demo").items.getById(1).select("Title", "Address").get();
    console.log(item);
    this.setState({
      selectedAddress: JSON.parse(item.Address)
    });
  }

Update location picker value to the SharePoint

 _updateListItem = async () => {
    const updatedItem = await sp.web.lists.getByTitle("Demo").items.getById(1).validateUpdateListItem(
      [{
        FieldName: "Address",
        FieldValue: JSON.stringify(this.state.selectedAddress),
      }]);
  }
Location searching mode

Download complete project in the blow GitHub link

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