0

I'm attempting to make a request from Axios to retrieve data from GitHub. I am receiving a failure error that makes sense, and I'm wondering if this is the expected behavior and this type is simply not possible from the client side, or if there is a way to make this request that I am simply missing:

componentDidMount() {    
    axios
      .get('https://github.com/users/lukeschlangen/contributions',{
        headers: {
          'Access-Control-Allow-Origin': '*'
        }
      })
      .then(res => {
        this.streakCounter(res);
      })
      .catch(err => console.log(err));
  }



  streakCounter(body) {
    const $ = cheerio.load(body);
    var data = [];
    $('svg').find('rect').each(function(index, element) {
        data.push({
            count: parseInt($(element).attr('data-count')),
            date: new Date($(element).attr('data-date'))
        })
    });

    var yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);

    data = data.sort(function(a, b) {
        return new Date(b.date) - new Date(a.date);
    }).filter(function(el) {
        return el.date.getTime() <= yesterday.getTime();
    });
    var streakCount = 0;
    for (var i = 0; i < data.length; i++) {
        if (data[i].count == 0) {
            break;
        }
        streakCount++
    }

    console.log('streakCount:', streakCount);

  }

My guess is that this is something GitHub might simply reject outright and that there is no way around this from the client side. This is the error I get in response:

Failed to load https://github.com/users/lukeschlangen/contributions: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404.

I'd prefer to do this without a server if possible, so I want to make sure before I throw in the towel.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Luke Schlangen
  • 3,722
  • 4
  • 34
  • 69
  • As mentioned in the accepted answer, you can use a CORS proxy. But rather than using a third-party proxy, you can set up your own very easily. See the answer at *How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems* section of the answer at *https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe/43881141#43881141*. You can deploy your own proxy on Heroku in only 2-3 minutes with just 5 commands. – sideshowbarker Aug 31 '18 at 11:31

1 Answers1

1

You won't be able to get around this in the front-end because it requires server-side changes by Github.

But, you could have your front-end ping your back-end, which then hits that URL and passes the information forward, or use a service to get around this like cors-anywhere.

Bricky
  • 2,572
  • 14
  • 30