Connecting Node/Express 4 with react-web-app — Part 2 (React setup)

Kushal V. Mahajan
Jul 27, 2017 · 2 min read

Hello Reacters and Noders alike.

We left at node setup in last part and we shall continue the same to wire it upto our React end (front-end) by all means.

In case you are coming directly to this post. Hit the link for part 1 — https://medium.com/@kushalvmahajan/i-am-about-to-tell-you-a-story-on-how-to-a-node-express-app-connected-to-react-c2fb973accf2

In case you haven’t installed create-react-app please do so by

npm install -g create-react-app

Now create a react boilerplate/app with

create-react-app client

Move to the freshly brewing react app

cd client

Now remember at this stage that our server is already running on PORT 9001 i.e. @ http://localhost:9001.

In case you are following this par too late or your server has gone down please spin up the node server again.

Inside of your client directory do

yarn start or npm start

At this point you are having your react app running at PORT 3000 ( by default ) and your express app at 9001.

Time to connect the dots…Oh! rather blocks of code. : P

The most important step towards this is to add proxy to react app

Head over and edit package.json file and add the below line after scripts somewhere.

"proxy": "http://localhost:9001"

Observe that this address is going to be the same as our node/express server. So do not mess up here for Javascript sake !

Now, What’s next ?

Do something useful with this connectivity or rather a POC.

Well, let’s modify our client/App.js a little bit

Let me run over the changes quickly.

state = {notes: []};

ensures that this.state.notes.map doesn’t breaks the app on load

componentDidMount() { fetch(‘/api/notes’) .then(res => res.json()) .then(notes => this.setState({notes})); }

This code actually connects the two apps. React uses the fetch method to make an Ajax call to get the notes from the end-point we established in part 1.

Inside the render method

{this.state.notes.map(note => <div key={note.id}> <span>{note.title}</span>- <span>{note.text}</span> </div> )}

The code simply iterated over the notes array returned from call.

So finally , we have reached to the end and you shall see something like

React express app

Questions below. Happy hacking !

Kushal V. Mahajan

Written by

Author of @turtlemint/redux-analytics and @turtlemint/mint-ui

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade