create-react-app - Fetch Local JSON (via AJAX)

Viewed 3852

I'm trying to do something rather simple with create-react-app, dynamically request a JSON file from somewhere else on the front-end. When I request the URL, Webpack just returns the index page of the app (with an HTTP 200).

I've tried placing the JSON files in both the src and public dirs, but it didn't make a difference (e.g., /src/data/stuff.json, /public/data/stuff.json).

I'm guessing webpack / something is preventing the request from going through.

Something like fetch('http://localhost:3000/public/data/stuff.json') just doesn't work. I see the request, but the response is just the default HTML.

Neither, of course, do http://localhost:3000/src/data/stuff.json or http://localhost:3000/data/stuff.json.

I'm fetching this dynamically rather than importing since I just want this one JSON file (I believe webpack would bundle all of them in the app; not to mention IRL the filename is dynamic, something closer to file-{date}.json with a large archive).

Would definitely love any and all help and bits of advice. Thanks! :)

1 Answers

create-react-app uses webpack-dev-server as a, uh, dev server. webpack-dev-server uses connect-history-api-fallback to serve the index.html file for every request (to allow for client-side routing). By default, the connect-history-api-fallback will NOT override paths with a dot (like /data/stuff.json). However, create-react-app disables this setting.

So you'll need to set disableDotRule to false here. You may need to eject in order to modify this config.

This setting depends on the server you're using though, so you may get different behavior when you aren't using webpack-dev-server.

Related