This article will show you how to build a personal blog using NodeJS +vuejs.

It is divided into three parts:

  1. Environment to prepare
  2. Blog Backend Management System (Admin)
  3. Back-end services (mainly providing admin and Web interfaces)
  4. Blog Front-end Presentation (Web)

Environment to prepare

  • nodejs

    Go directly to the official website to download the latest stable version of the good, below is the download link: nodejs.org/en/download…

  • vue-cli

    This is a powerful build tool that makes it easy to manage a VUE project without requiring more WebPack configuration. Recommended global installation:

    npm install --global vue-cli
    Copy the code
  • mongodb

    The database to be used at the back end. Go directly to the official website to download the corresponding system version, pay attention to download the Server version. Download: downloads.mongodb.com/

Blog backend management system

Project creation

Start by creating a basic VUE back-end project using the following command:

    vue create admin
Copy the code

For some of the options that appear, simply select the default. The directory structure is as follows:

The router integration

Vue-cli can easily integrate routing:

vue add router
Copy the code

Element – the UI integration

For convenience, we use some of the components provided by Element-UI for the back-end page implementation, so we integrate element-UI into it:

vue add element
Copy the code

Prompt options, all select the default.

Well, the basic structure of the back-end project is now complete. You can start it by running the following command:

npm run serve
Copy the code

The default page is as follows:

Basic Page Layout

You can use element-UI layout-container and copy the sample code into the home.vue template. One thing to note here, however, is that since we want only the right side to change when switching the left menu, the left side should remain the same, we need to use

. Mount the right-side changes to

.

Creating a Category Page

First create a categoryedit. vue file and then add the route. Routing Note here that the mutable page on the right should be used as a child route for the Home component. In this way, the content of the CategoryEdit page is displayed at the position of the

that we defined earlier.

Ok, so when we type “http://localhost:8080/#/categories/create” in the browser, the CategoryEdit page will come up. The specific page content is not introduced here. Are all elements of element-UI.

Due to limited space, other pages are not introduced in detail here, the specific source has been open source to GitHub.

The final project page structure should look like this:

It is divided into three parts: classification management, article management and user management.

The interfaces used in the pages are described in the following Server section.

The back-end service

This part is implemented by NodeJS + mongodb.

The project build

  1. Start by creating a folder server in the root directory (the same directory as admin).
  2. Create a package.json file and initialize one using the following command
    npm init
    Copy the code

    Select all defaults.

  3. Depend on installation. The following dependencies are mainly used by the back end.
    "cors": "^ 2.8.5"// Allow cross-domain requests"express": "^ 4.17.1"// Backend framework"mongoose": "^ 5.6.12." "// Database"nodemon": "^ 1.19.2"// The backend service is automatically restarted after the file is changedCopy the code
  1. Create a new index.js file after the above dependencies are installed.
const express = require('express')
const cors = require('cors') const app = express() // Allow cross-domain app.use(cors()) app.use(express.json()) app.listen('3000', async(req, res) => {
  console.log("http://localhost:3000")})Copy the code
  1. To start the back-end service, run the following command:
    nodemon start index.js
Copy the code

Route definition

Create a Router folder and an admin folder as the admin interface. You can create a Web folder as the Web interface. Create an index.js file in the admin folder

module.exports = app => {
  const express = require('express') const router = express.router ()'/getData', async (req, res) => {
    res.send("hello world")
  })
  
  app.use('/admin/api/rest', router)
}
Copy the code

Notice that we’re exporting a function here, and one of the nice things about this is that we can pass in arguments, so here we pass in app as a parameter.

In the index.js file in the root directory, we need to introduce the following:

require('./routers/admin/index')(app) // Execute the function directly and pass app as an argumentCopy the code

When the input “http://localhost:3000/admin/api/rest/getData” in the browser, see “hello wrold.”

Connecting to a Database

Create a new folder db and create a new db.js file:

module.exports = app => {
  const mongoose = require('mongoose')

  mongoose.connect('mongodb://localhost:27017/myblog', {
    useNewUrlParser: true})}Copy the code

Mongodb starts on port 27017 by default after installation. Myblog is the name we gave the database.

Then you need to import db.js in the index.js file.

require('./db/db')(app) 
Copy the code

Create the model

Create a new models folder, and under that folder create category.js as the model for the classification.

const mongoose = require('mongoose')

const schema = new mongoose.Schema({
  title: {type: String}
})

module.exports = mongoose.model('Category', schema)
Copy the code

I’m just going to define a category name “title” for now

Data query

The data in the Categories table can be queried using the following code in the Routers /admin/index.js interface.

Router.get ('/categories', async (req, res) => {
    const res = await Category.find()
    res.send(res)
  })
Copy the code

When the input “http://localhost:3000/admin/api/rest/categories” in the browser can get the categories table data.

Ok, with the introduction above, we should be able to implement some simple add, delete, change and check operations.

The middleware

In the process of development, we are bound to run into a problem.

As mentioned above, back-end admin mainly includes three modules: classification management, article management and user management.

Each module will involve add, delete, change and check operations. If we define our own set of add, delete, change and review interfaces for each module, it is bound to produce a lot of duplicate code, and in the case of multiple categories, the duplicate code will be more serious. So consider customizing a middleware.

Create a folder called Middleware, and then create a resource. Js file (we can think of each category as a resource) to add, delete, change, or query resources, except for the name of the resource.

module.exports = options => {
  return async (req, res, next) => {
    const inflection = require('inflection') const modelName = inflection.classify(req.params.resource) req.Model = require(`.. /models/${modelName}`)
  
    next()
  }
}
Copy the code

We use the Inflection library, which we need to install, and use inflection. Classify to singular the parameters passed in as the model names.

Change the routers/admin.index.js mode to the following one

Router.get ('/', async (req, res) => {
    const data = await req.Model.find()
    res.send(data)
  })

  app.use('/admin/api/rest/:resource', resourceMiddleware(), router)
Copy the code

Well, due to the limited space, some other content will not be introduced, the detailed code can refer to GitHub.

Blog Front-end Presentation (Web)

Project construction

This part is similar to admin. A new Web project needs to integrate router, but does not need Element-UI. For details, please refer to the project construction introduction of back-end management system above.

Topic selection

Theme part I am directly from the Jekyll Themes theme library selected one, due to the time is not so much, plus is doing their own play, so steal a lazy. Post the original author Liberxue here.

Traffic statistics

Traffic statistics here used a free open source library not garlic son, very lightweight, very simple to use.

The main page

At the end

Ok, so much for now, there are a lot of content will not unfold. If you have any questions please leave a message.

As I am a front-end background, do six or seven front-end. The back end is also just touched shortly, so the front part of the introduction of the above may be less, relative to the back end will be more, if there are any mistakes welcome to correct.

Source code has been open sourceGitHubIf you think it is of some help to yourself, I hope you can give me aStar.