Created
February 6, 2017 14:22
-
-
Save TBag/f9cc4ee5acdab75064abbfa78eb0b1c3 to your computer and use it in GitHub Desktop.
How to set headers and body for SPFx httpClient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { HttpClient, IHttpClientOptions, HttpClientResponse } from '@microsoft/sp-http'; | |
private makeRequest(value1: string, value2: string, value3: string): Promise<HttpClientResponse> { | |
const postURL = "https://REST-API-URL"; | |
const body: string = JSON.stringify({ | |
'name1': value1, | |
'name2': value2, | |
'name3': value3, | |
}); | |
const requestHeaders: Headers = new Headers(); | |
requestHeaders.append('Content-type', 'application/json'); | |
requestHeaders.append('Cache-Control', 'no-cache'); | |
//For an OAuth token | |
requestHeaders.append('Authorization', 'Bearer <TOKEN>'); | |
//For Basic authentication | |
requestHeaders.append('Authorization', 'Basic <CREDENTIALS>'); | |
const httpClientOptions: IHttpClientOptions = { | |
body: body, | |
headers: requestHeaders | |
}; | |
console.log("About to make REST API request."); | |
return this.context.httpClient.post( | |
postURL, | |
HttpClient.configurations.v1, | |
httpClientOptions) | |
.then((response: Response): Promise<HttpClientResponse> => { | |
console.log("REST API response received."); | |
return response.json(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You will likely need to setup some kind of proxy function if you're pulling your hair out trying to get it to work - here's a good article on the topic https://github.com/ravichandran-blog/SPFx/tree/master/spfx-cors