Full Stack Development Starter - React and Nodejs

Full Stack Development Starter - React and Nodejs

Get started using React with Express.js

When I went from being a UI & UX designer to a programmer I had literally no idea what I was doing. What made it worse was that I didn’t have any mentorship or guidance on how to move forward. All of my coworkers were Salesforce developers and hadn’t built any full-stack web apps with industry standard technology. It was up to me to pave the way forward with a new technology stack and deployment strategy.

With no idea of what to even Google and almost no concept of what it takes to build a full-stack application, I headed into the technological wilderness to find my path. After several weeks of research about coding languages and hosting platforms I finally had a full-stack application completed and running on Node.js and Angular 2+.

I often wonder what this project, or even the next couple of years of development, would have looked like if I had mentorship while figuring all of this out. That’s my goal with this article - to act as a simple mentor and get you started down the full stack trail.

React and Node.js

We’re gonna start with a full javascript stack. This can make developing and deploying full-stack applications a breeze since you only need to know one language.

There are several ways you can structure the client and server folders, but for today’s example, we’re going to keep it as simple as possible! That way you can expand it on your own in the future!

Prerequisites Node.js installed - You can download it here.

Get Started

First things first - let’s create our React app:

$ npx create-react-app react-node
$ cd react-node
$ yarn build

If you’ve never used npx before - it’s basically an execution library. Instead of having to install create-react-app globally and then use the global command to create the app, you can use npx!

At this point our React app is ready to go! We’re not going to do anything else with it right now since all we’re trying to do is serve it from a server.

We’ll need to add Express to our project and then create a file. I’ll name mine server.js.

$ yarn add express
$ touch server.js

Now, open the file and paste these lines:

const express = require('express');
// instantiates express so we can use the middleware functions
const app = express();

// Node’s native tool for working with files. 
const path = require('path');

// set a default port in case the host isn’t configured with one
const port = process.env.PORT || 3000;

app.use(express.static(path.join(__dirname, 'build')));

app.get('*', (req,res) => {
   res.sendFile(path.join(__dirname+'build/index.html'));
});

app.listen(port, () => console.log(`Listening on port ${port}`));

Since the file is a javascript file and we’ll the node command to start it up, the runtime is established as Node.js.

On 2 two we’ve instantiated “app” as our Express application. Just like REST requests, Express has get, post, put, and delete functions. But if you’d like to use a single middleware function for all of the HTTP verbs, the use function is your jam.

On line 6 the Express app loads the build folder. Without this line the code would fail since Express wouldn’t be able to send the index.html file to the browser.

The app.use(...) function is what actually serves the root of our React app to the browser. Notice that it’s only being served when on a GET request, but it is serving the file at all routes. This way when our React app begins routing, the server is returning the index.html file and making sure the React app is running.

To serve your app, make sure you’re in the root of the project and type:

$ node server.js

Whala! Full-stack app - done. You’re serving your pre-built React app with Express. But let’s add one more route to make sure you’re well on your way to becoming a full-stack developer.

First, let’s add the body-parser library.

$ yarn add body-parser

Now let’s import it and setup our new route:

const express = require('express');
const app = express();
+ const bodyParser = require('body-parser')
const path = require('path');
const port = process.env.PORT || 3000;

app.use(express.static(path.join(__dirname, 'build')));
+ app.use(bodyParser.json());

+ app.post('/new-route', (req, res) => {
+   let name = req.body.name;
+   res.send(
+        {greeting: `Hello ${name}`}
+   );
+ })

app.get('*', (req,res) => {
   res.sendFile(path.join(__dirname+'build/index.html'));
});

app.listen(port, () => console.log(`Listening on port ${port}`));

This new route will take a POST request at a route matching “/new-route” and return an object with a greeting. Notice that we’ve also added another app.use(...) function that will parse the value of the body in the req object.

Now onto the React!

import React, { useState } from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
 const [greeting, setGreeting] = useState('');

+ fetch("/new-route", {
+   method: 'POST',
+   headers: {
+     'Content-Type': 'application/json',
+   },
+   body: JSON.stringify({name: 'Luke Duke'})
+ })
+   .then(res => res.json())
+   .then((result) => {
+       setGreeting(result.greeting);
+   })
+   .catch(error => console.log(error))
 return (
   <div className="App">
     <header className="App-header">
       <img src={logo} className="App-logo" alt="logo" />
       <p>
         Edit <code>src/App.js</code> and save to reload.
       </p>
       + {greeting &&
       +  <h2>{greeting}</h2>
       + }
       <a
         className="App-link"
         href="https://reactjs.org"
         target="_blank"
         rel="noopener noreferrer"
       >
         Learn React
       </a>
     </header>
   </div>
 );
}

export default App;

We added the “useState” import and added a hook for the response from the server. We also added a fetch() function that POSTs into our server with a name. The JSX renders the greeting when it’s set.

Note: You do not have to return an object from the Express app. Typically real world applications return a non-string variable, but you can return any type from Express.

Finally, rebuild the React and start up the server to see your app work!

$ yarn build
$ node server.js

And that is our Javascript all-the-way example! There is a ton of great documentation on the Express.js Framework page to help you along on your way.