Original link:

In this article, I’ll walk you through creating a simple React project and connecting it to our own Node/Express API.

This article will cover some technical details that you may not be familiar with, so I won’t go into too much detail here. I will leave some links in the mentioned places, so that interested readers can click on them to read and learn more.

Project source code for this tutorial:

The main purpose of this article is to provide a practical guide to creating a client from scratch and connecting it to the server.

Before you begin, make sure that node.js is successfully installed on your local development environment.

Create the main project directory

Open your computer terminal and open the folder where you want to save the entire project. Then enter the next two instructions to create the main project directory.

mkdir my_awesome_project
cd my_awesome_project
Copy the code

Creating the React application

We use the most brief approach here. Facebook provides a scaffolding for creating a React application, create-react-app. You can create a React project called client by entering the following command on the terminal.

npx create-react-app client
cd client
npm start
Copy the code

A brief description of what the following commands do:

  1. Create a React project using NPM’s NPX and name it Client
  2. CD go to the client directory
  3. NPM start Runs the project next, type http://localhost:3000/ in your browser. Unsurprisingly, you’ll see the React welcome page. Congratulations, you’ve learned how to create a basic React application!

To stop running the project, press Ctrl+ C on the terminal.

Creating an Express application

This process is as straightforward as opening your my_awesome_project folder in your terminal. Here, we will use the Express Application Generator to create an Express Application framework and name it API

npx express-generator api
cd api
npm install
npm start
Copy the code

These instructions do in turn:

  1. Use NPM’s NPX to install the Express-Generator
  2. Create an Express app using Express-Generator and name it API.
  3. The API folder is displayed
  4. Install the installation packages that all projects depend on
  5. Run the application. Open your browser again and go to http://localhost:3000/. You will see the Express welcome page. If you’ve made it this far, congratulations! You’ve learned how to create a native Express application! Don’t forget to stop the application by pressing CTRL + C in terminal.

Configure Express Api routing

Next, use your accustomed IDE and open the my_awesome_project folder. If you created the React and Express applications using the above two steps, you will now see the client and API folders.

  1. In the API folder, open the bin/ WWW file and change line 15 to 3000 (port number) to 9000. Since we will be running both front-end and back-end applications at the same time, we will change the back-end port number here to avoid port conflicts.
  2. Still in the API folder, we go to the API/Routes directory, create a testapi.js file there and type the following code
var express = require("express");
var router = express.Router();

router.get("/".function(req, res, next){
    res.send("API is working properly");
})

module.experts = router
Copy the code
  1. Next we go to the API /app.js file and insert a new line at line 24
app.use("/testAPI".testAPIRouter);
Copy the code
  1. All you did was tell Express to use the “testAPIRouter” route, so don’t forget to introduce this file at the top. So let’s import our own routing file by typing the following code at line 9
var testAPIRouter = require("./routes/testAPI");
Copy the code
  1. Congratulations! You have successfully configured your first route!

At this point you can run the Express application, (NPM into API directory in the terminal, and then input the start), and then open the browser to http://localhost:9000/testAPI, you can see Express run successful information: The API is working properly”

Connect the React project to the Express API

  1. Next we’ll focus on the client side and open the “my_awesome_project/client/app.js” file in your code compiler.
  2. In this file, we write a simple Fetch API request to Fetch data from the back end. Add the following code to the render function in the class declaration:
constructor(props){
    super(props);
    this.state = {apiResponse: ""};
}

callAPI(){
    fetch("http://localhost:9000/testAPI")
        .then(res => res.text())
        .then(res => this.setState({ apiResponse:res }))
}

componentWillMount(){
    this.callAPI();
}
Copy the code
  1. In the next render function, you can replace the code between and with:
<p className="App-intro">{this.state.apiResponse}</p>
Copy the code

With all this input, let me briefly explain what we did:

  1. In lines 6-9, we insert a constructor that declares the default state for the page
  2. In lines 11-16, we add a new function called callAPI. This function sends the request to the API and stores the returned response in this.state.apiResponse
  3. On lines 18-20, we insert a React lifecycle function componentDidMount(), where we call callAPI. It will be executed after the page has been rendered.
  4. At the end, we write one in the render function

    Tag to display the information we get from the API.

Cross domains?

Above, we have basically completed the construction of the project and the configuration of the front and back end connections. But if you now run both the back-end and the front-end projects on the terminal and open the browser http://localhost:3000/, you will find that they are not running successfully. If you open Chrome Developer Tools at this point, you will see the legendary cross-domain error:

Failed to load http://localhost:9000/testAPI: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
Copy the code

Instead of going into the details of what went wrong, we’ll offer a simple solution. We add a package called CORS to the API to allow cross-domain requests from the server

  1. Go to your API directory in terminal and enter the following instructions to install CORS
npm install --save cors
Copy the code
  1. Open the my_awesome_project/ API /app.js file in the compiler.
  2. Add in line 6
var cors = require("cors");
Copy the code
  1. On line 18, type the following command to enable Express to use CORS
app.use(cors());
Copy the code

Congratulations to you! So let’s see what happens

  1. Run your front-end client and back-end API at the same time (need to open both terminals, use NPM start respectively)
  2. Open your browser to http://localhost:3000/ and you’ll see the React icon with a welcome message, along with a message that reads “API is working properly.”

conclusion

This article does not cover the details of the knowledge points, but provides a hands-on guide to creating a full stack project. You can find resources for project engineering on Github.

In the next article, I’ll show you how to connect this project to the MongoDB database and how to configure the entire project using Docker.

As a good Friend of mine says:

Be Strong and Code On!!!
Copy the code

. and don’t forget to be awesome today!