0

I have written below code in SPFx Webpart to upload file to Sharepoint Library. It gives me error sometimes like TypeError : Failed to fetch. Can anyone give me some idea what this error signifies and how can it be resolved.

function uploadFile(myfile, target) {
        var dfd = $.Deferred();
        sp.web.webs.filter("Title eq 'DMS'").get().then(webData => {
            const _web = Web(webData[0].Url);
            //for files < 10 MB
            if (myfile.size <= 10485760) {
                _web.getFolderByServerRelativeUrl(target).files.add(myfile.name, myfile, true).then((result) => {
                    dfd.resolve(result);
                }).catch(err => {
                    dfd.reject(err + ". Error in method: uploadFile while uploading File");
                });
            }
            //for files > 10 MB
            else {
                _web.getFolderByServerRelativeUrl(target)
                    .files.addChunked(myfile.name, myfile)
                    .then(({ file }) => file.getItem()).then((item: any) => {
                        dfd.resolve(item);
    
                    }).catch(err => {
                        dfd.reject(err + ". Error in method: uploadFile while uploading File");
                    });
            }
        }).catch(err => {
            dfd.reject(err + ". Error in method: uploadFile while getting web");
        });
        return dfd.promise();
    }

1 Answers1

0

Looks like you have not initialized the pnpjs (sharepoint) library. The error "failed to fetch" usualy means there is a CORS request rejection. Check out the "getting started" document: https://pnp.github.io/pnpjs/getting-started/

class HelloWorldWebPart {
  ....
  public onInit() {
    ...
    sp.setup(this.context);  //< this part seems to be missing?
Nikolay
  • 10,752
  • 2
  • 23
  • 51
  • we have initialized the pnpjs library in the parent component and this issue is not frequent for us and everything is happening in the same domain. So, how can this be a course issue just trying to understand. – Akshay Gandotra Nov 11 '20 at 05:11
  • Do you see the request that gets blocked in the Developer tools ("Network" tab)? – Nikolay Nov 11 '20 at 07:25