Home > Software engineering >  How to share data locally between node app and react
How to share data locally between node app and react

Time:10-15

The thing is - I have nodeJS app (not an API) and a react app. I need to share some json data from node app to react, so that react is able to display it.

I tried to write json to file, but obviously I cannot access fyle system from react as it is executed in browser. I though of some kind of local db (mongo, for instance), but I have no idea how I can connect to the mongo from react.

Any ideas on how that can be implemented?

CodePudding user response:

I think that the best way to do that is using an API endpoint. Create a route on your NodeJS app using express on any NodeJS framework, return your json data on the response of the API, then fetch the API endpoint from your client (React). It is very recommended to avoid working with FS (Files system). The database solution is also a good one but more expensive and more code, so I guess the first idea is the best. Good luck

CodePudding user response:

If you are rendering index html/js file of React using NodeJS, you can try passing JSON string as variable and render it on page as hidden input string that has that JSON value, which you can retrieve and parse on page load using React.

I am not familiar with Node, but this is possible in other backend frameworks and templating engines like Flask and Jinja.

  • Related