Introduction to super easy fullstack app with React and Node.js(express)
What comes into your mind when you hear “Implement frontend and backend functionality by yourself”? I know it sounds super hard and requires you to bunch of knowledge. It’s kind of true if you go deeper into server side, but it’s also easy to get to start with them. In article, I would like to explain…
- How to create an app with React
- How to set up and run a server using Node.js(express)
- How to connect React to Node.js
Let’s get dive into a fullstack world!
1.How to create an app with React
If you have already created React app before, this section should be easy. What we need to create a React app is just one command
npx create-react-app [APP-NAME]
For this time, I named the app name as client
so I can explicitly tell it’s a client side(frontend) directory. Once you create an app with React, let’s open the project directory. Be careful not to open the directory with the name of the app name that you just created because we will put server side(backend) files outside the directory. In short, open the directory that contains the client side directory. Now you’ll see the workspace in your editor like as follows.
Next up, let’s open the terminal(for VS Code user, just press cmd + j
), go to the client side directory, and install axios that enables us to fetch data from a server with commands of
cd client
andnpm i axios
Now we are ready for actual coding.
1. Open client/src/App.js
.
2. Import useState
from react and axios
from axios.
3. Declare a state named message
using useState
.
4. Delete the code inside <div className="App"></div>
.
So far, App.js should look like so.
Now let’s finish up the actual elements inside the component. We will add
1. One h1
element with a content of like CLICK US
just for title.
2. Two button
elements with onClick
event of handleClick1
and handleClick1
.
3. One h2
element with a content of the state that we declared earlier, message
.
4. Create two async functions with a name of handleClick1
and handleClick2
, where we implement API call from a server that we will create in a while.
Then the code will be like this.
The code is not completed yet, but let’s leave client side code and get stared to write server side code!
2.How to set up and run a server using Node.js(express)
In creating server side functionality, Node.js with a framework of express is very popular because it’s simple, easy to understand, and the best part is that you can find tons of resources on the internet. It might sounds strange, but it’s popular because it’s already popular.
First things first, let’s do some basic setup for Node.js and express. At this point, just make sure your current directory is root directory, outside the client side directory.
1. Install express
and cors
using npm.
2. Create a file called index.js
.
3. Import express
and cors
in index.js
and do some setup.
When we import something into index.js
or other files in server side directory, we useconst [METHOD] = require('[PACKAGE/LIBRARY]')
insted ofimport [METHOD] from '[PACKAGE/LIBRARY]'
That might be a bit confusing for the first time, but just think of it as a normal declaration of methods.
When it comes to setup of index.js, there are lots of basic expressions depending on what kind of functionality developers want to implement. For this sample application, let’s make it as simple as possible. What we need for setup is just a few lines as below.
const express = require('express') // Import express
const cors = require('cors') // Import corsconst app = express() // Call express as a functionapp.use(cors()) // Enable corsapp.listen(8080, (req, res) => { // Run a server
console.log("SERVER IS RUNNING ON 8080");
})
Next up, we’ll add some functions that will be called when the corresponding API request is called. This time, let’s name the endpoints /get-data1
and get-data2
. Then in the callback function, we just return a string as response.
app.get('/get-data1', (req, res, next) => {
res.send("HELLO FROM SERVER")
})app.get('/get-data2', (req, res, next) => {
res.send("GOOD NIGHT FROM SERVER")
})
.get
means the request should be GET method, and /get-data1
and get-data2
means the corresponding callback function will be called when the request URL is /get-data1
or /get-data2
. Also, what cors
does is to allow the server being accessed from another server. We used localhost:3000
as a client side server and localhost:8080
as a server side, so we need to make sure that the request from localhost:3000
is allowed by using cors
.
Now the entire contents in index.js
should look like so.
In order to run the server, use the command of
node index.js
Or, if you want the server to watch any change instantly, you can try nodemon
which can be installed and run with the command of
npm i -g nodemon
andnodemon index.js
Some extra
We just implemented a super simple server side functionality, but usually we import more packages or libraries and call methods like session
, dotenv
, or like express.json()
depending required functionality.
session
is used to store some data that can be accessed through the server. We use it when we want to store token, user data, or other stuff.
dotenv
provides us a way to access environmental variables that should be hidden from public. React provides us a way to access them in default, but other than that, we need to import this package to read environmental variables.
express.json()
converts object data that have been passed from client side into json data which is readable in server.
3. How to connect React to Node.js
Now we are back to client side directory and ready to write a code to fetch data from a server. For some of you who have called API request from any service, this part should be pretty much the same as the one we do for them. We made these two functions async functions because generally getting data from a server takes more time than javascript executing next line. If we miss this part, the response will be empty and it causes troubles on your program.
Actually the contents inside handleClick1
and handleClick2
is very similar because I separated these to functions just to show that we can send a request to multiple endpoints by modifying the URL. Each function is like
const response = await axios.get('http://localhost:8080/getdata-1(/2)')
setMessage(response.data)
The only difference between handleClick1
and handleClick2
is the last number of the endpoint.
That’s pretty much about client side coding, and it should look like as follows.
Now it’s time to run the client side server with the command of
npm start
Make sure your backend server is running and you run npm start
in the client side directory.
If both server is running, you should see a screen with a heading and two buttons like below when you access http://localhost:3000
.
Then when you click either BUTTON 1 or BUTTON 2, you’ll see the text that has been sent from the server you are running.
Hope you got the idea of communication between client side(frontend) and server side(backend). The example that created has only minimum functionality, so if you get interested, feel free to go deeper into server side operations. You’ll be able to meet bunch of useful packages and libraries. Although the complicated system might bother you but they are complicated for some reasons like security matters. As you get more used to it, you’ll definitely find it interesting and be able to your skill way broader.
Cheers!