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(); | |
}); | |
} |
@manjeetjagtap Check if you've enabled CORS on the AppService that is hosting your Web Service
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am calling custom web service hosted into dedicated server through POST method from SPFx. I am fetching token from https://graph.windows.net and passing into header. But I am getting below error in POST method.
Access to fetch at 'https://MyServer/WebService.svc/PostMethod' from origin 'https://MYDOMAIN.sharepoint.com' has been blocked by CORS policy: Request header field cache-control is not allowed by Access-Control-Allow-Headers in preflight response.