Where is HttpClient and related classes in SPFx 1.1?
-
08-02-2021 - |
Question
I am finally able to get started using SPFx. Stuck on 2016 / SPFx 1.1.
The documentation for the HttpClient
class says it's in the @microsoft/sp-http
package. However, the Yeoman generator did not include that package when I scaffolded out a new 2016/1.1 project.
I can get to IWebPartContext
in @microsoft/sp-webpart-base
, and pass a context object from the outer web part into a component. And the context object has a httpClient
property. However, to make web requests, I gather that I will need to use some other classes (notably HttpClientResponse
if I want to get anything back from the server).
Where are those classes, if not in @microsoft/sp-http
? I am assuming the generator did not include a dependency to that package because that package is not compatible with v1.1? Or do I need to just add it myself?
Here are the packages the Yeoman generator added by default:
"dependencies": {
"@microsoft/sp-core-library": "~1.1.0",
"@microsoft/sp-lodash-subset": "~1.1.0",
"@microsoft/sp-office-ui-fabric-core": "~1.4.0-0",
"@microsoft/sp-webpart-base": "~1.1.0",
"@types/es6-promise": "0.0.33",
"@types/react": "0.14.46",
"@types/react-addons-shallow-compare": "0.14.17",
"@types/react-addons-test-utils": "0.14.15",
"@types/react-addons-update": "0.14.14",
"@types/react-dom": "0.14.18",
"@types/webpack-env": "1.13.1",
"react": "15.4.2",
"react-dom": "15.4.2"
},
"resolutions": {
"@types/react": "0.14.46"
},
"devDependencies": {
"@microsoft/sp-build-web": "~1.1.0",
"@microsoft/sp-module-interfaces": "~1.1.0",
"@microsoft/sp-webpart-workbench": "~1.1.0",
"@types/chai": "3.4.34",
"@types/mocha": "2.2.38",
"ajv": "~5.2.2",
"gulp": "~3.9.1"
}
Solution
As mentioned in the comments, @microsoft/sp-http
package is available for use in SP 2016. But it is in the form of an upstream dependency, so it is not visible in the package.json
file.
Yes, it quite confusing, but unfortunately that's the way it works :(
To use it, you can add the below import statement in your code and consume it in your methods:
import { HttpClient, HttpClientResponse } from "@microsoft/sp-http"
If you are working with SharePoint REST APIs, then would suggest that you use SPHttpClient
. The HttpClient
is primarily for consuming APIs outside of SharePoint.