javascript - create-react-app - Fetch Local JSON (via AJAX) - Stack Overflow

admin2025-04-18  1

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! :)

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! :)

Share asked Sep 26, 2017 at 17:14 numoniumnumonium 1312 silver badges7 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744931991a275212.html

最新回复(0)