DEV Community

Cover image for Full-Stack React & Node.js - Create the server
Dave
Dave

Posted on • Updated on

Full-Stack React & Node.js - Create the server

First create a folder node-server at the same level as folder react-client

Inside the node-server folder, use a shell/CLI to enter this command to create a package.json file:

npm init -y
Enter fullscreen mode Exit fullscreen mode

The -y flag means that package.json will be filled with defaults. You can edit the file later to add your name and repository details, etc.

Next run this to install some dependencies:

npm i -S express body-parser cors morgan
Enter fullscreen mode Exit fullscreen mode

i is shorthand for install
-S is shorthand for -save

Create index.js and paste in this code:

const express = require('express');
const cors = require('cors');
const morganLogger = require('morgan');
const bodyParser = require('body-parser');

const env = process.env.NODE_ENV || 'development';
const app = express();

if (env === 'development') {
  app.use(cors());
}

app.use(morganLogger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

// 404 route not found!
app.use(function (req, res, next) {
  const error = 'Here be dragons. Route not found';
  console.info(`404 error! ${error}`)
  res.status(404).send(error);
});

const port = 4011;

app.listen({port}, async () => {
  const baseUrl = `http://localhost:${port}`;

  console.log(`Server running at: \t @ ${baseUrl}/`);
});
Enter fullscreen mode Exit fullscreen mode

I will briefly explain the packages we are importing.

express is the web framework.

The cors package disables "cross origin resource sharing", where origin is a URL and resources are assets like images. The purpose of the cors policy is to prevent a website from pointing their image links to a different site and stealing hosting costs. In development we allow cors because we run both the React client and the Node server on one machine, each in their own process (live you could deploy both to the same folder and avoid cors issues). The port numbers on the server and client URL's are needed so the traffic (HTTP requests and responses) can be sent to the correct process. Port numbers are included in the browser decision on the origin of the server response

Your browser sees the website is on port 3000 but it attempts to fetch data from port 4011. Even though they both run on localhost, because the port numbers are different, to a browser they are different websites entirely! If we didn't disable cors, this request would violate the same-origin policy and be denied!

body-parser is middleware that parses incoming requests to extract data for us, in this case json (it also includes a few other parsers that can be useful).

morgan is a middleware request logger. In this case we pipe all messages to the console (you could instead write to a file). This is one of the most essential things to include in any node server. For troubleshooting and debugging, seeing all requests logged to your console is pure gold!

You might notice our server returns no data, has no routes defined, but has a 404 handler. I always add a 404 handler first! When your app grows and has complex routing, getting a clear message, a "final destination" for unmatched routes is essential for development and debugging.

Next edit package.json, and change the "scripts" section to add an additional line:

  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
Enter fullscreen mode Exit fullscreen mode

Finally you should be able to run your Node.js server with this command:

npm run start
Enter fullscreen mode Exit fullscreen mode

Run this in the same folder as the package.json file

When the console outputs a message saying the server is running, paste this URL into a browser: "http://localhost:4011/"

You should see a text message: "Here be dragons. Route not found"

This is good. We received an HTTP 404 error, which is what we expect as, currently, our server returns no data and has no routing paths defined.

You now have a working client and server. Next we will return some data.

Code repo: Github Repository

Top comments (0)