getting list items in SPFx application
-
13-12-2020 - |
Pergunta
trying to retrieve list items via get method of spHttpClient object in SPFx webpart project.
Here code piece;
private readItems(): void {
this.setState({
status: 'Loading all items...',
items: []
});
this.props.httpClient.get(`${this.siteUrl}/_api/web/lists/getbytitle('${this.props.listName}')/items?$select=Title,Id`,
SPHttpClientConfigurations.v1)
.then((response: Response): Promise<{ value: IListItem[] }> => {
debugger;
return response.json();
})
.then((response: { value: IListItem[] }): void => {
debugger;
this.setState({
status: `Successfully loaded ${response.value.length} items`,
items: response.value
});
}, (error: any): void => {
this.setState({
status: 'Loading all items failed with error: ' + error,
items: []
});
});
}
when this function triggered here is the response from server;
Message is obvious, but I really need to get list items in this web address. how can I achieve it ?
I created this project with yeoman generator("yo @microsoft/sharepoint") is there any configuration to make it run http:// instead of https://
as you know default address of application is "https://localhost:4321/temp/workbench.html"
Solução
Open your SPFx webpart on the SPO workbench page as below:
https://tenantname.sharepoint.com/_layouts/15/workbench.aspx
Here, https://localhost:4321/temp/workbench.html
is the local SharePoint Workbench page. Your code needs to run on the SharePoint Workbench page hosted in SharePoint.
On that page, you need to add your webpart (in my case, its the helloworld webpart) and configure the properties to get data from list.
To test in the local workbench you will need a mock store that returns mock data.
Create a new file inside the src\webparts\helloWorld folder named MockHttpClient.ts.
Copy the following code into MockHttpClient.ts:
import { ISPList } from './HelloWorldWebPart';
export default class MockHttpClient {
private static _items: ISPList[] = [{ Title: 'Mock List', Id: '1' },
{ Title: 'Mock List 2', Id: '2' },
{ Title: 'Mock List 3', Id: '3' }];
public static get(restUrl: string, options?: any): Promise<ISPList[]> {
return new Promise<ISPList[]>((resolve) => {
resolve(MockHttpClient._items);
});
}
}
Reference - SPFX - Connect your client-side web part to SharePoint
Outras dicas
OPs Question was: Is there any configuration to make it run http:// instead of https://
Means (for security reasons) you can't call an HTTP:// URI from a secure HTTPS:// site
after you recieved his error in the console;
there will be a button (far left or right in the URL bar) to override security and allow HTTP endpoints
You can now call HTTP:// endpoints, but only from *Your* current Browser session
You can't overrule this setting with code because that defeats the whole purpose of security