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
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
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 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 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
// 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:
// 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 in your browser:
$ npm start
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
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
})
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 so the client runs on localhost:3001.
Let's go to localhost:3001.
Hmmm...We don't see the name. What's the error? If you open the developer tool, you will see this:
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
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())
Now, stop the server and restart it:
Voila! We have just created a full stack application.
In the next article, I will implement some feature in this application.
Top comments (10)
I think it's better for deploy
Devlopment
create-react-app package.json support proxy=localhost:3000
Production
jsx
Great! In this case, I will need only Node server to run the application. Thank you for the comment!
What a brief, lovely post! Keeping stick to and hoping for another one from the oven. Best
of luck to you.
Thank you! There is more to come :)
Short and informative 😀
Thank you!
Very good!!! ☺️
Thank you for reading! :)
Nice and lean content -- keep it coming!
Thank you so much. A very clear guide for beginners to understand how Nodejs and React work together.