Experiencing CORS issue when using an external node module in React

552 Views Asked by At

Problem

I'm using the howlongtobeat npm module in my React app, however when I do a search query as documented in the howlongtobeat docs I get the following CORS error in the console:
Access to XMLHttpRequest at 'https://howlongtobeat.com/search_results.php' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here's my basic React app that I've been testing in:

import { HowLongToBeatService, HowLongToBeatEntry } from "howlongtobeat";

let hltbService = new HowLongToBeatService();

function App() {
  hltbService.search("halo").then((result) => console.log(result));

  return (
    <div>something</div>
  );
}

export default App;

Things I've Tried

  • I tested using the howlongtobeat node module in a Vanilla JavaScript file and that worked. So this issue seems to only be effecting me in React.
  • I tried the Chrome plugin Allow CORS: Access-Control-Allow-Origin and that fixes it locally, but obviously won't work in production (I'm trying to deploy to GitHub Pages).
  • I tried modifying the URL in the node package's js file to use the cors-anywhere proxy, but my app didn't seem to be picking up the changes I made to the node module's file.
  • I tried adding a proxy entry into my package.json (e.g. "proxy": "localhost:3000"), but that doesn't seem to work. I'm also not sure what URL I'm supposed to enter here (I tried https://howlongtobeat.com as well as the cors-anywhere proxy I hosted from above.

Any ideas on how I can fix this?

1

There are 1 best solutions below

1
On

The web service you're using is preventing other sites from accessing its data client-side. Without the appropriate Access-Control-* headers from that service, you won't be able to do this directly.

I tried adding a proxy entry into my package.json (e.g. "proxy": "localhost:3000")

You're on the right path, but unless you're actually running a server that is reading this config, it won't matter.

You need to run some sort of proxy server to proxy the data to an origin you can control, so that your page is hosted from either the same origin, or that you have something like Access-Control-Allow-Origin: * in the response headers.

See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS