1

API Post call returns "Failed to Fetch"

I have created a SPFx Web Part using React. It implict authenticates and acquires access token. When i am calling graph api for GET it works fine. When i am calling graph api for POST call for creating user. It is creating user in AD as well as throws error of "Failed to Fetch" and not getting updated user object in response.

Find code below to call this api.

private static createADUser(accessToken: string, httpClient: HttpClient, objUser: string): Promise<IUser> {
    return new Promise<IUser>((resolve: (newUser: IUser) => void, reject: (error: any) => string): void => {
        httpClient.post(`https://graph.microsoft.com/v1.0/users`, HttpClient.configurations.v1, {
            headers: {
            'Content-type': 'application/json;odata.metadata=none',
            'Authorization': 'Bearer ' + accessToken,
            },
            body: objUser
        })
        .then((response: HttpClientResponse): Promise<any> => {
            return response.json();
        }).then((objUser: any) => {
                resolve(objUser);
            }, (error: any): string => {
                var strError: string = error.message;
                if (strError.toLowerCase() == "failed to fetch")
                    resolve(null);
                else
                    reject(strError);
                return;
        });
    });
}

Does anyone know about it? What may be the cause of it and what will be the solution? Thank you in advance.

1 Answer 1

0

It gets working now. I had just changed single quote to double quote in post URL and objUser name to responsebody in then variable declarations.

Could not figure out actual logic behind it but it luckily works fine for me.

Please find working code below:

private createADUser(httpClient: HttpClient, accessToken: string, objUser: string): Promise<IUser> {
    return new Promise<IUser>((resolve: (newUser: IUser) => void, reject: (error: any) => string): void => {
      httpClient.post("https://graph.microsoft.com/v1.0/users", HttpClient.configurations.v1, {
        headers: {
          'Content-type': "application/json;odata.metadata=none",
          'Authorization': "Bearer" + accessToken
        },
        body: objUser
      })
        .then((response: HttpClientResponse): any => {
          return response.json();
        }).then((responsebody: any) => {
          var newUser = WpadManagement.getUser(responsebody);
          resolve(newUser);
        }, (error: any) => {
          reject(error.message);
        });
    });
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.