user3649361
user3649361

Reputation: 954

Using ReactJS with NodeJS

I have an application which need to interact with UI and perform various CURD operation to database in the backend,

At present I we have a angular 1.2 application which have the UI and another node application and for every and the angular application sends http request to node application for every interaction needed, so here I have two different services.

I wanted to combine these operations into a one single service means UI(React) and node in one single service, like react inside node, when I start node server I should be able to access by UI also ,I am using express in node, what is the best way to do to use ReactJS with Node in a single service.

Upvotes: 0

Views: 890

Answers (2)

Saud
Saud

Reputation: 417

Hope you are using express along with nodejs. You could place the react application folder inside your node application folder in some folder named client. Then from node app you could do the following to server react files:

var app = express();
app.use(express.static(path.join(__dirname, 'client')));

After all the application specific routes to serve your apis, provide the following to serve index.html for all other get requests.

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname+'/client/index.html'));
});

Upvotes: 2

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

In order to execute http requests from a react application (it doesn't matter if you backend is node), I recommend using fetch api:

fetch(url)
  .then(response => response.json())
  .then(response => /* Do what you need with it */)

Axios also works quite good and provides the same result:

axios.get(url)
  .then(response => response => /* Do what you need with it */)
  .catch(error => console.log(error))

Upvotes: 0

Related Questions