Home > Net >  NetworkError when attempting to fetch resource using Facebook SDK in React and Webpack
NetworkError when attempting to fetch resource using Facebook SDK in React and Webpack

Time:04-13

I am trying to use the Facebook SDK for javascript, I want the user to log in so I can get the token that FB returns, the process completes successfully but I get the error "NetworkError when attempting to fetch resource." in the console.

This is my code to call the facebook sdk and connect with my app:

export function initFacebookSdk() {
  return new Promise(resolve => {
    // wait for facebook sdk to initialize before starting the react app
    window.fbAsyncInit = function () {
      window.FB.init({
        appId: <appId>,
        cookie: true,
        xfbml: true,
        version: 'v13.0'
      });
      resolve()
    };   
  });
}

export function loadFacebookSDK(d, s, id){
  return new Promise(resolve => {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) { return; }
    js = d.createElement(s); js.id = id;
    js.src = "https://connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
    resolve()
  })
}

And this is the function I call to login with Facebook:

export const FbLogin = () => {
  return new Promise( resolve => {
    loadFacebookSDK(document, "script", "facebook-jssdk")
    initFacebookSdk()
    window.FB.login(response => {
      if (response.authResponse) {
        resolve(response);
      } else {
        resolve(response);
      }
    }, {scope: 'email'});
  })
}

This part of the code is the one that calls the function and obtains the token correctly:

  const getFbToken = async (e) => {
    e.preventDefault()
    const data = await FbLogin();
    console.log(data);
  }

I need help to know what I am doing wrong and how to prevent the error from appearing, for now I am performing the tests locally.

Help :(

CodePudding user response:

NetworkError means that the request was unable to go through. The most common causes of this are:

  • The request has been blocked by the user, such as an ad-blocker (common for Facebook)
  • The request is not allowed by the endpoint's CORS policy
  • The endpoint is miss-typed, or protocol (https) is missing
  • The endpoint is offline (unlikely for Facebook SDK)
  • The client is offline, or (if running on a server) firewall rules are preventing access

In the case of OP, their ad-blocker was blocking the request to Facebook. This is common, as the same SDK is used for collecting user data and displaying Facebook ads.

To prevent a poor user experience for users with an ad-blocker, you'd likely want to show a meaningful error message if the request was blocked. A neat solution to this is described in this post.

  • Related