DEV Community

Luke Frauhiger
Luke Frauhiger

Posted on

Full Stack Development Starter 1 - React and Nodejs

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.

Three Part Series

We’re gonna be working with React and using three different server-side languages: Javascript(Node.js), Ruby, and Python. Node, Ruby, and Python are some of the most widely used server-side languages in full-stack development because they’re very easy to spin-up on and are quite fast to develop on. Each of them also has a tightly bound middleware that makes serving HTTP(s) requests incredibly easy. For Node this is Express.js, for Ruby it’s Rails and for Python it’s Django. We’ll get into this more later on. But I’ll stop gabbing now and we can get to the code!

nodejs plus reacts

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.

Note: I’m primarily a javascript developer but it’s beneficial to learn a scripting language like Python or Java. But you do you. Javascript all-the-way does work!

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.

Stay tuned for articles on serving React with Ruby and Python.

This article is cross-posted on my website as well.

Top comments (0)