Вопрос

I'm having trouble getting the correct site context for @pnp/sp. It works fine in workbench but not when I deploy to a site and add to a modern page. My api calls are being made to /_api/sitepages and not the root web. Am I missing something? I'm using the react spfx yeoman template

Это было полезно?

Решение

You need to initialize the pnp library with the SPFx context.

For that you need to add the below code in your webpart's .ts (TypeScript) file:

1) Add the below import statement

import pnp from "sp-pnp-js";

2) Add/Update the onInit method:

public onInit(): Promise<void> {

  return super.onInit().then(_ => {

    pnp.setup({
      spfxContext: this.context
    });

  });
}

If however, you are using the newer pnp js (@pnp/sp) scoped libraries, you need to add the below code in the webpart's .ts (TypeScript) file:

1) Add the below import statement

import { sp } from "@pnp/sp";

2) Add/Update the onInit method:

public onInit(): Promise<void> {

  return super.onInit().then(_ => {

    // other init code may be present

    sp.setup({
      spfxContext: this.context
    });
  });
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с sharepoint.stackexchange
scroll top