Todd Baginski's Blog - A SharePoint, Mobile, Office365, PowerApps and Azure Blog

HOW TO: Set the body and headers for the SharePoint Framework (SPFx) httpClient

6 February 2017

Comments:

Off
 February 6, 2017
 Off
Grand View Looking Northwest

In my article How To: Run a Microsoft Flow from a SharePoint Framework (SPFx) web part I set the headers and body when I called a Microsoft Flow with the SharePoint Framework (SPFx) httpClient class.

How To: Run a Microsoft Flow from a SharePoint Framework (SPFx) web part

In this post, I have simplified the code to succinctly demonstrate how to set the body and request headers when making a request with the SharePoint Framework (SPFx) httpClient class.  Refer to the code snippet below.

First, import httpClientIHttpClientOptions, and HttpClientResponse from the @microsoft/sp-http npm package.

To create the body for the POST request use JSON.stringify for a JSON payload or manually create a JSON payload.  If you are not working with a JSON payload then assemble the body accordingly.

To set the headers for the request, first create the Headers class and add the appropriate headers to it.  In this example you can see several commonly used headers.  Notice I show how to set the Authorization header for both OAuth 2.0 and Basic authentication scenarios.  You would never use both of these Authorization headers at the same time; I just included them both for reference.

Next, add the body and the headers to the IHttpClientOptions interface.

Finally, invoke the appropriate method on the SPFx httpClient to make the request. In this example, I am using the post method.  The approach is exactly the same when you use the get method.

When you call the post or get methods you pass in the following parameters:

url – the URL to fetch
configuration – determines the default behavior of HttpClient; normally this should be the latest version number from HttpClientConfigurations
options – additional options that affect the request

The httpClient returns a promise that contains the result.

Note: I suggest you read this article by Chris O’Brien to learn more about the SPFx httpClient class.

Comments are closed.