Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 525
numonium Avatar asked Sep 26 '17 17:09

numonium


People also ask

Can AJAX be used with React?

You can use any AJAX library you like with React. Some popular ones are Axios, jQuery AJAX, and the browser built-in window. fetch.

How do I use AJAX in React app?

APIs are used for fetching data from the server and using AJAX and API we call data asynchronously and show it in our HTML. You can make API requests by using browser build in fetch function or third party libraries like Axios.

How get data from localStorage in react JS?

Note: In order to store data in localStorage , we must first convert it to JSON string using the JSON. stringify() function. And when we want to retrieve it, we will parse the data using JSON. parse() , converting the JSON string back to a JSON object.


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.

like image 92
Sidney Avatar answered Sep 20 '22 17:09

Sidney