Setting up a Full Stack React Application

So you've built an API and you've tested it in Postman. You're now ready to build a front end interface using React!

Setting up a client-side application that accesses an API running on localhost sounds messy but it's actually really simple!

Folder Structure

Right now your project folder looks like this:

/my-api-project
  index.js
  /routes
    example.js
  /models
    example.js
  package.json

Go ahead and make a folder called /client and use create-react-app to initialize a new React app within /client:

/my-api-project
  /client
    /node_modules
    package.json
    /public
    README.md
    /src
  index.js
  /routes
    example.js
  /models
    example.js
  package.json

Setting up a Proxy

Right now in Postman you're making requests to http://localhost:<PORT>/example-endpoint. That means you'd have to use the same URL when you're making requests using axios. While this is ok in development mode it won't work when your app is in production (you would have to run your personal computer 24/7!).

create-react-app lets you specify a proxy URL that will be used while developing so that you don't have to go back and change all your URL origins when you deploy your website to the public.

Add the following "proxy" property to /client/package.json:

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.3.2",
    "react-dom": "^16.3.2",
    "react-scripts": "1.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:<PORT-GOES-HERE>"
}

Now, instead of making axios requests like this:

axios.get("http://localhost:8080/example")  

You should write them like this:

axios.get("/example")  

create-react-app will automatically set the request origin to whatever the "proxy" setting is in package.json while in development mode, but will reset it to wherever it is being served from in production mode without you having to do anything!

Now you are ready to start building your front-end!
You can treat /client as if it were just any other React project you've made so far in the course.