How to create a React-Node.js application
Tags: webdev, react, node, beginners
Published: 2021-03-30 03:27:42

![React Node.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y63ie8bmktwik5w3mhlg.png)
React is a JavaScript library for building web applications. Since it won't load in browsers without a web server, we need some mechanism to load the React application's `index.html` containing all the browser dependencies such as CSS and JavaScript files. In this article, I will walk through how to use Node.js as a web server loading React assets and accepting API calls from the React application.

###0. Prepare tools###
Before you start, make sure Node and NPM are installed on your computer. If they are not, check [Nodejs.org](https://nodejs.org/en/).

###1. Create the project directory###
Let's start with creating the project directory. In the directory where you would like to save your project, run:
```
$ mkdir my-app
$ cd my-app
```

###2. Create a React app###
It is the best way to start building a React application using Facebook's [create-react-app](https://reactjs.org/docs/create-a-new-react-app.html#create-react-app) that sets up your development environment. Let's name the application "client."
```
$ npx create-react-app client
```

###3. Create a Node.js app###
Create a directory named "api" for the Node.js application:
```
$ mkdir api
$ cd api
```
Now you need to add a `package.json` file to manage dependencies. You can do it by running a [CLI command](https://docs.npmjs.com/creating-a-package-json-file#running-a-cli-questionnaire) and answering the questions:
```
$ npm init

# Click enter to skip the questions and use the default values.
{
  "name": "api",
  "version": "1.0.0",
  "description": ""
}
```
[Express.js](https://expressjs.com/) is a Node.js web application server framework. You can easily install it by running:
```
$ npm install --save express
```
Now, let's create `server.js` for the API implementation:
```
$ touch server.js
```
```javascript
// api/server.js

const express = require("express")
const app = express()

app.listen(3000, () => {
  console.log("app listening on port 3000")
})
```
The `listen` method runs a web server on port `3000`.

###4. Configure routes###
Let's set a GET method route on the homepage to see if the server is working:
```javascript
// api/server.js

const express = require("express")
const app = express()

app.get("/", function(req, res) {
  res.send("It's working!")
})

app.listen(3000, () => {
  console.log("app listening on port 3000")
})
```
Start the web server and go to [localhost:3000](http://localhost:3000) in your browser:
```
$ npm start
```
![server response](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f6pzuskltpe564eslaj5.png)
If you see this message in your browser, your Node.js application is ready!

###5. Connect the React client to the Node.js server###
Let's use the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) to retrieve data from the web server. In the `App.js` file of the client:
```javascript
import React from "react"

class App extends React.Component {
  state = {
    name: ""
  }

  componentDidMount() {
    fetch("http://localhost:3000")
      .then(res => res.json())
      .then(data => this.setState({ name: data.name }))
  }

  render() {
    return (
      <h1>Hello {this.state.name}!</h1>
    )
  }
}

export default App
``` 
To send `name` to the client, rewrite the response of the GET request in `server.js` of the server:
```javascript
app.get("/", function(req, res) {
  res.send({"name": "Jane Doe"}) // Should be json format
})
```
Now, let's start both applications and see the result. First, run `npm start` in the server:
```
$ cd api
$ npm start
```
Then, open another tab in your terminal window and run `npm start` in the client as well:
```
$ cd ../client
$ npm start
```
Make sure you start the server first on [localhost:3000](http://localhost:3000) so the client runs on [localhost:3001](http://localhost:3001).

Let's go to [localhost:3001](http://localhost:3001).
![Error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eheynyxkn6xsa33s26dh.png)

Hmmm...We don't see the name. What's the error? If you open the developer tool, you will see this:
![Error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tdsn9vhb9dkwbp9jqh6u.png)
This happens because a [cross-origin request](https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api#cross-origin_requests) occurred when the `Fetch` request was made. To solve this, we need to install the [CORS](https://www.npmjs.com/package/cors) package in the server:
```
$ npm install --save cors
```
Add these lines to `server.js` in the server to require cors and tell express to use it:
```javascript
const cors = require("cors")

app.use(cors())
```
Now, stop the server and restart it:
![React app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1bsbql0mktfnxnq0jarz.png)
Voila! We have just created a full stack application.

In [the next article](https://dev.to/junko911/building-a-word-counter-appliction-in-node-js-using-axios-3p5c), I will implement some feature in this application.