Importing JSON files in React app from backend

Viewed 407

I'm writing a React app and I would like to load content from local JSON files.

I tried using import Data from "./info/websiteData.json" and it works fine on localhost. However, when I built the app for production, it doesn't include the JSON files and causes errors. So I think I have to keep the JSON on the backend?

If I keep the JSON files on the backend (say, outside of the public_html folder), how do I get their contents when the page loads? Would I have to use XMLHTTPRequest for this? What would you do?

Thanks for your help!

2 Answers

Yes and yes.

  1. If you have static files in your backend that are used by your server you can store them alongside the backend source files (outside the public).
  2. Your frontend can only fetch stuff from your backend via some kind of API. So you will need to implement an endpoint that will return this resource (in your case a JSON file)

you can send a request to the backend and receive the data in JSON format. sending data as a response to a request it's a task that backend developer should take care of

Related