Shaun Collins
Posted on November 19, 2019
SEO Friendly Blog
I have been learning to code for about 3 years now and have built countless Blogs so I thought it was about time I shared what I have learnt! I will lay out this build in small chunks as I go through the process. All feedback is welcome including criticism but please be kind!
Step One
First lets make the folder structure with mkdir 'project-name' then create 2 further directories 'backend' and 'frontent'. Change directory to backend and run npm init -y to create a package.json file and install express, body-parser, cookie-parser, nodemon, cors, morgan and dotenv. When the install has completed don't forget to create a .gitignore file and .env file, enter your node_modules and .env in the gitignore file as you don't want to upload these to Github!
Now, still in your backend directory create server.js file and populate it with:
const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const cors = require("cors");
require("dotenv").config();
const app = express();
// Middlewares
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(cors());
// Routes
app.get("/api", (req, res) => res.json({ time: Date().toString() }));
// Port
const port = process.env.PORT || 8000;
app.listen(port, () => console.log(`App running on port: ${port}`));
Then lets change the json file so:
{
"name": "backend",
"version": "1.0.0",
"description": "SEO Blog Backend",
"main": "index.js",
"scripts": {
"start": "nodemon server.js"
},
"keywords": [
"node",
"react",
"seo"
],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cookie-parser": "^1.4.4",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mongoose": "^5.7.11",
"morgan": "^1.9.1",
"nodemon": "^1.19.4"
}
}
Make sure you set your enviroment variables in your env file:
NODE_ENV=development
PORT=8000
CLIENT_URL=http://localhost:3000
Now we are ready to start our server with npm run start. Visit localhost:8000/api and you should see your local time displayed in json format, if you don't get a json formatter extension to parse the output.
Step Two
Next we need to run some requests to the API, for that visit https://www.getpostman.com/ and download Postman. As we will be sending requests from localhost: 3000 with our frontend React app we need to configure the CORS Middleware as:
// CORS Cofig
if (process.env.NODE_ENV == 'development') {
app.use(cors({ origin: `${process.env.CLIENT_URL}`}));
}
Otherwise we get Access-Control-Allow-Origin error in your browser, Postman will not be affected by this.
Step Three
Next lets connect our Database, for this you have to either open a MongoDB Atlas account or download MongoDB to your machine and run it locally whatever is your preference, personally I like to use Atlas it is very easy to setup. Create a cluster and name it what you like. To connect your app just choose connect to application and mongodb supplies a link, copy to your clipboard and return to your env file to paste in your link like:
NODE_ENV=development
PORT=8000
CLIENT_URL=http://localhost:3000
DATABASE='mongodb+srv://USERNAME:PASSWORD@seoblog-dhag5.mongodb.net/DBNAME?retryWrites=true&w=majority'
Then in server.js file require in mongoose and configure your DB connection:
const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const mongoose = require("mongoose");
require("dotenv").config();
const app = express();
// Connect Database
mongoose
.connect(process.env.DATABASE, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
})
.then(() => console.log("Database is Connected!"))
.catch(err => console.log(err));
Restart your server and you should see:
[nodemon] 1.19.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
App running on port: 8000
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
App running on port: 8000
Database is Connected!
As I said, you can install MongoDB locally if that is your preference, here are some links:
Installing MongoDB on MAC
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/
Installing MongoDB on Windows
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/
Installing Robo3T
If you use Atlas you can download MongoDB Compass and install from your Cluster, just choose connect with Compass!
If you use local mongodb then connect with this string in your env file:
DATABASE_LOCAL='mongodb://localhost:27017/seoblog'
Don't forget to adjust your server file to accommodate this change!
Step Four ROUTES
Create a new routes folder in the root of your backend directory and the create a blog.js file in that folder.
const express = require('express');
const router = express.Router();
router.get("/", (req, res) => {
res.json({ time: Date().toString() });
});
module.exports = router;
// and in your server.js file require your blog.js file and setup Routes Middleware
// Routes
const blogRoutes = require('./routes/blog');
const app = express();
// Connect Database
mongoose
.connect(process.env.DATABASE_LOCAL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
})
.then(() => console.log("Database is Connected!"))
.catch(err => console.log(err));
// Middlewares
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(cookieParser());
// Routes Middleware
app.use(blogRoutes);
Then you can remove the API route in server.js and use the api as the first argument in your new middleware:
app.use('/api', blogRoutes);
Step Five Controllers
Next as with the routes we need to make a controllers folder in the root directory with a blog.js file.
// controllers blog.js
exports.time = (req, res) => {
res.json({ time: Date().toString() });
};
// Then in your routes blog.js
const express = require("express");
const router = express.Router();
const { time } = require("../controllers/blog");
router.get("/", time);
module.exports = router;
Tomorrow I'll come back and show how I add User SignUp and SignIn Functionality.
Happy Coding
Posted on November 19, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.