Tagged: ExpressJS, JavaScript, MongoDB, NodeJS, ReactJS
- This topic has 0 replies, 1 voice, and was last updated 2 years, 5 months ago by
Precious.
- AuthorPosts
- February 21, 2020 at 12:26 pm #86391Spectator@precious
Web developers who use Javascript libraries as their primary tool for web development often face challenges when setting up a new computer for development. This stems from the fact that there is always a lot of updates to be made, configurations and installations to be perfected before the laptop is deemed ready for production. This stage ranks as one of the most difficult these programmers often face (from beginner to advanced) because it practically determines whether or not a system is fit to run web applications – from bugs to be fixed, to software installations and sometimes a slight modification in the operating system settings. Fortunately, this article is here to help!
Javascript has long been described as the programming language of the web – and recently it has proved to be much more than is expected -in the sense that there is a high increase in the set of diverse, feature-rich and efficient libraries built from Javascript and made available for web programmers to choose from, specialize in and build applications with.
Often times, these libraries and frameworks are limited in what they can build – hence the need for complimentary languages to suffice in the areas not covered. For instance, ReactJS is a javascript framework designed for building front-end applications, ExpressJS allows one to build the backend application, while NodeJS creates a runtime environment. When these three are used in complimentary ways, a fully functional and dynamic application is plausible. A combination of programming languages that compliment each other is called a Stack. Examples of stacks include;
- MEAN: Made up of MongoDB (Database), ExpressJS (Back-end), AngularJS (Front-end) and NodeJS (Container).
- MERN: MongoDB (Database), ExpressJS (Back-end), ReactJS (Front-end) and NodeJS (Container).
- PERN and PEAN: PostgreSQL (Database), ExpressJS (Back-end), ReactJS (Front-end) / AngularJS (Front-end) and NodeJS (Container).
In this article, the MERN stack would be used to setup a computer system for web development using JavaScript.
Requirements
To begin, one must have the following on standby or physically active;
- A Personal Computer or PC (preferably running on Windows 10) – with NodeJS installed on it.
- Access to the Internet – you would be doing a lot of installations and you need constant supply of data for all of them.
- The Visual Studio Code Editor – it is selected for its efficiency in organizing code.
- Command Prompt Interface.
- A web browser to test your configurations.
Step 1: Installing Dependencies
- Simply open your command prompt and create a folder for any destination – this folder would be the ultimate folder for all installations you will need during this setup. Give it a name of your choice – you will need it.
- Open this folder through the Visual Studio Editor.
- Open a terminal in code editor (VS Editor) and type the following commands;
npm init -y
– this code initializes the project and creates a file named package.json where all installations you will make during this setup could be stored. - Install the Node Server called ExpressJS for handling the back-end of the application. To to this, run the following code ‘npm install express`.
Create a file inside this directory named Index.js and run the following codes inside it;
const express = require('express'); const exp = express(); const port = process.env.PORT || 5000; exp.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); exp.use((req, res, next) => { res.send('Welcome to Express'); }); exp.listen(port, () => { console.log(<code>Server running on port ${port}</code>) });
In the above snippet, there is a piece of code that allows you to run cross-origin requests (CORS) during the development and testing of your program. This is the code;
exp.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); });
After this is set – you may now start your server by running the command
node index.js
in your terminal. If all goes well, you should see an output like the following screenshot.On the browser, type localhost:5000 and press Enter, You should see an output saying Welcome to Express as is seen in the screenshot below.
Step 2: Setting up Routes, Models and the Database
When designing your application, you would want to send, retrieve and manipulate data in your database collection. For this cause, it is necessary to setup a database, build a model to be used in defining the structure and configuration of the database (schema) and define the roadmap for the connection between the front-end and the back-end of your application. This is where Routing, Modeling and Database implementation comes in.
To setup and configure your routes;
- Create a folder named routes using the following command:
mkdir routes
. - Create a file named config.js and insert the following piece of codes into it.
const express = require ('express'); const router = express.Router(); router.get('/todos', (req, res, next) => { }); router.post('/todos', (req, res, next) => { }); router.delete('/todos/:id', (req, res, next) => { }) module.exports = router;
- Since we are using MongoDB as the database, we would need to install Mongoose – the MongoDB package manager on the app. So, head on to your terminal and type
npm install mongoose
– a complete installation should have the following output (or a resemblance).
- Create a folder named model in your project root folder (testing as is seen in the snapshot) using the commands
mkdir models
- Inside models, create a .js file named todo.js. It is this .js file that contains the structural configurations of your database, such as data types, operations possible, validation requirements etc.
- Inside todo.js, insert the following snippet of code
const mongoose = require('mongoose'); const Schema = mongoose.Schema; //create schema for todo const TodoSchema = new Schema({ action: { type: String, required: [true, 'The todo text field is required'] } }) //create model for todo const Todo = mongoose.model('todo', TodoSchema); module.exports = Todo;
- After this is done, update routes.js file to accept the model created – using this piece of code.
const express = require ('express'); const router = express.Router(); const Todo = require('../models/todo'); router.get('/todos', (req, res, next) => { //this will return all the data, exposing only the id and action field to the client Todo.find({}, 'action') .then(data => res.json(data)) .catch(next) }); router.post('/todos', (req, res, next) => { if(req.body.action){ Todo.create(req.body) .then(data => res.json(data)) .catch(next) }else { res.json({ error: "The input field is empty" }) } }); router.delete('/todos/:id', (req, res, next) => { Todo.findOneAndDelete({"_id": req.params.id}) .then(data => res.json(data)) .catch(next) }) module.exports = router;
- For the database, I recommend mlab for its free testing and connection abilities. You could create your account and get a free cluster worth 512mb for testing and development – higher offers require paid subscriptions. After you have setup your database, update your Index.js file to look like this.
const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const routes = require('./routes/api'); const path = require('path'); require('dotenv').config(); const exp = express(); const port = process.env.PORT || 5000; //connect to the database mongoose.connect(process.env.DB, { useNewUrlParser: true }) .then(() => console.log(<code>Database connected successfully</code>)) .catch(err => console.log(err)); //since mongoose promise is depreciated, we overide it with node's promise mongoose.Promise = global.Promise; exp.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); exp.use(bodyParser.json()); exp.use('/api', routes); exp.use((err, req, res, next) => { console.log(err); next(); }); exp.listen(port, () => { console.log(<code>Server running on port ${port}</code>) });
- In the above snippet, the process.env file was employed in order to access environmental variables (for database connection). But it has not been created, neither has its extension ( dotenv ). To do this, create a file named .env in your root folder and edit it by adding the following snippet.
DB = 'mongodb+srv://:@mycluster-vm5k6.mongodb.net/test?retryWrites=true&w=majority'
In the space for user and password, add your username and password used in creating the cluster on mlab.- To access the variable stored in the .env file, install the node package called dotenv – simply head on to your terminal and run
npm install dotenv
– complete installation should have an outlook like this.
- After the installation, configure it in your index.js file by adding this at the top of the file:
require('dotenv').config()
– it is worthy to note that this system of using environment variables saves you from constantly writing all credentials for connection in your application code, by making sure that the configuration used for connectivity is kept secret. - Start your server again by running
node index.js
in your terminal. - To test and see that our configurations are working fine. You can employ the services of Restful API testing applications like POSTMAN or INSOMNIA. For this article, INSOMNIA is used – ensure you test all endpoints (GET, POST, DELETE etc) to ensure that your API is securely connected on all sides. The screenshot below contains the result of testing INSOMNIA using the POST request and the API
http://localhost:5000/api/todos
and it returned200 OK
which means it was successful.
Step 3: The Front-end Create a React Application
This is where the first part of this article concludes. We will create a react application inside the project folder to see if it runs. If it does, the next step would be to run operations between the front-end and the back-end. But this will be discussed in the next article, and when this happens, this one would be referenced.
To begin;
- Head into your terminal and run the following command
npm create-react-app client
this creates a react application inside the project folder – which is where all the your react codes will be based. A successful creation and installation of the dependencies should show something like this screenshot below.
- Then install the body-parser dependency that allows node to break down all requests sent to and from your sever into meaningful components and interpret them. Simply run
npm install body-parser
. After complete installation, you should have an output like the image below.
Step 4: Test-Run the React Application
To run the react application, you will need to install two other dependencies – namely concurrently – for running multiple commands at a time, and nodemon – a package from npm that listens for changes in any part of the application and quickly makes an update. To install them and run the react application, do the following.
- Open your terminal and run
npm install concurrently --save -dev
- After it has installed, run
npm install nodemon --save -dev
- Open your package.json file in your main project folder and ensure that all packages you have installed are accurately represented.
- In your package.json file change the dev configuration under scripts to run on npm instead of yarn – thus, instead of running
yarn run start-watch
, it should havenpm run start-watch
. Then save the file. - Open a fresh terminal and enter this command
npm run dev
– this will run the application from the dev configuration in package.json. A successful build and run should have your front-end running on port 3000 and your backend running on port 5000. As described in the screenshots for the terminal and browser below.
The next part of this article would show the baby steps in running commands between the front-end and the back-end of your setup. Stay tuned.
- AuthorPosts
- You must be logged in to reply to this topic.