DEV Community

Junko T.
Junko T.

Posted on • Edited on

How to create a React-Node.js application

React Node.js
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.

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


Enter fullscreen mode Exit fullscreen mode

2. Create a React app

It is the best way to start building a React application using Facebook's create-react-app that sets up your development environment. Let's name the application "client."



$ npx create-react-app client


Enter fullscreen mode Exit fullscreen mode

3. Create a Node.js app

Create a directory named "api" for the Node.js application:



$ mkdir api
$ cd api


Enter fullscreen mode Exit fullscreen mode

Now you need to add a package.json file to manage dependencies. You can do it by running a CLI command and answering the questions:



$ npm init

# Click enter to skip the questions and use the default values.
{
  "name": "api",
  "version": "1.0.0",
  "description": ""
}


Enter fullscreen mode Exit fullscreen mode

Express.js is a Node.js web application server framework. You can easily install it by running:



$ npm install --save express


Enter fullscreen mode Exit fullscreen mode

Now, let's create server.js for the API implementation:



$ touch server.js


Enter fullscreen mode Exit fullscreen mode


// api/server.js

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

app.listen(3000, () => {
  console.log("app listening on port 3000")
})


Enter fullscreen mode Exit fullscreen mode

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:



// 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")
})


Enter fullscreen mode Exit fullscreen mode

Start the web server and go to localhost:3000 in your browser:



$ npm start


Enter fullscreen mode Exit fullscreen mode

server response
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 to retrieve data from the web server. In the App.js file of the client:



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


Enter fullscreen mode Exit fullscreen mode

To send name to the client, rewrite the response of the GET request in server.js of the server:



app.get("/", function(req, res) {
  res.send({"name": "Jane Doe"}) // Should be json format
})


Enter fullscreen mode Exit fullscreen mode

Now, let's start both applications and see the result. First, run npm start in the server:



$ cd api
$ npm start


Enter fullscreen mode Exit fullscreen mode

Then, open another tab in your terminal window and run npm start in the client as well:



$ cd ../client
$ npm start


Enter fullscreen mode Exit fullscreen mode

Make sure you start the server first on localhost:3000 so the client runs on localhost:3001.

Let's go to localhost:3001.
Error

Hmmm...We don't see the name. What's the error? If you open the developer tool, you will see this:
Error
This happens because a cross-origin request occurred when the Fetch request was made. To solve this, we need to install the CORS package in the server:



$ npm install --save cors


Enter fullscreen mode Exit fullscreen mode

Add these lines to server.js in the server to require cors and tell express to use it:



const cors = require("cors")

app.use(cors())


Enter fullscreen mode Exit fullscreen mode

Now, stop the server and restart it:
React app
Voila! We have just created a full stack application.

In the next article, I will implement some feature in this application.

Top comments (10)

Collapse
 
maqi1520 profile image
Alex Ma • Edited

I think it's better for deploy

Devlopment

create-react-app package.json support proxy=localhost:3000

Production

// Have Node serve the files for our built React app
app.use(express.static(path.resolve(__dirname, '../client/build')));

// Handle GET requests to /api route
app.get("/api", (req, res) => {
  res.json({ message: "Hello from server!" });
});


// All other GET requests not handled before will return our React app
app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '../client/build', 'index.html'));
});
Enter fullscreen mode Exit fullscreen mode

jsx

componentDidMount() {
    fetch("http://localhost:3000/api")
      .then(res => res.json())
      .then(data => this.setState({ name: data.name }))
  }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
junko911 profile image
Junko T.

Great! In this case, I will need only Node server to run the application. Thank you for the comment!

Collapse
 
emmanfreak profile image
Oblivion • Edited

What a brief, lovely post! Keeping stick to and hoping for another one from the oven. Best
of luck to you.

Collapse
 
junko911 profile image
Junko T.

Thank you! There is more to come :)

Collapse
 
mukul_singhal profile image
Mukul Singhal

Short and informative 😀

Collapse
 
junko911 profile image
Junko T.

Thank you!

Collapse
 
sturpin profile image
Sergio Turpín

Very good!!! ☺️

Collapse
 
junko911 profile image
Junko T.

Thank you for reading! :)

Collapse
 
cedricmurairi profile image
Cédric Murairi

Nice and lean content -- keep it coming!

Collapse
 
pakhei_chau_5c02fda7829c profile image
Jacky Chau

Thank you so much. A very clear guide for beginners to understand how Nodejs and React work together.