A preface.


The article mainly in the macro form to talk about a full stack development project, very suitable for the primary stage of learning the front end of the small white, appropriate full stack development is front-end learning in the primary stage must have some skills. Most people know that a full-stack development project is mostly composed of: e-commerce system + social system + blogging system. But what we don’t know is how. And the project THAT I’m going to talk about today is to help you answer that question, using blogs as an example.

Said in the previous

Not yet installed vUE? Here is a vue installation tutorial, very detailed oh! Of course, if your VUE foundation is not very good, here is a video to help you improve your VUE project. Technical fat vue video tutorial

This is a project based on vue & mongodb, if you have not installed mongodb, you can refer to the mongodb installation tutorial, simple operation, easy to get started, want to understand how to build a full stack project with Vue? Just take a few minutes to read this article!


Ii. Questions raised: Blog (Blog)


  • Train of thought
  1. In the whole stack project, we need to establish a framework that separates the front end (Web) from the back end (server). In addition, you need to have the idea of developing in the background (admin). I’ll tell you what the difference is.

Background: provides the system manager can see the page, and tourists, users can not see the page; Front-end: the code in which the programmer is programming; Back end: In contrast to the front end, writing code is basically provided for the front end to call, and is something that doesn’t have to deal with the UI. For example: logical layer.

  1. Front-end we need to carry out the page operation, back-end database connection, back-end management in the end how to execute?

Front-end (Web) We need to create a new front-end project using VUE, which is relatively good user experience and easier to use than React, and is a single page application. The back end (server) is mainly used to add, delete, change and check blog articles, providing API. Background (admin) is to help the administrator to deal with things, this article does not involve background content. So we build the general idea of full stack development!


Iii. Specific explanation

  • Project creation process: create blog folder in vue directory, create server folder and admin folder in blog folder.

The backend server

1. First we need to initialize the server filenpm init -yAfter that, we need to create a folder db in the server folder. In the db folder, we need to create a file db.js, which is created to connect to the local database.Localhost :27017 is the default mongodb addressThis is a common question. After connecting to the local database, it is available in mongodbuse myblogSwitch to the blog system. The code is as follows:

Module. exports = app => {// mongodb driver const mongoose = require(// module.exports = app => {// mongodb driver const mongoose = require('mongoose');
   mongoose.connect('mongodb://localhost:27017/myblog', {
     useNewUrlParser: true// Property is set totrueTo avoid"Using the current URL string parser is not recommended"Warning, compatible with Moogoose's new URL connection mechanism. })}Copy the code

2. Next, what we need to do is to establish a connection to the database. Let’s create a new index.js file in the server folder. There is an introduction express scaffolding in the code that we can pass throughyarn add expressTo add Express scaffolding. For those of you who have questions about Express, there is also information aboutExpress scaffolding explanation. The code is as follows:

const express = require('express'); const app = express(); // import db.js from es6'./db/db')(app); // Database connectionCopy the code

Run the project using Node index.js. If no error is reported, the database connection is successful.

3. Now we will start to build the table, the table design is divided into independent modules to build. Think about what tables we need to create to do a blog. The first table we must build is the Article table: article.js. In mongodb, we build tables called collections. The code is as follows:

// create table collection // 1. Const mongoose = require('mongoose')

const schema = new mongoose.Schema({
  uid: {
    type: mongoose.SchemaTypes.ObjectId,
    ref: 'User'
  },
  title: { type: String },
  isTop: { type: Boolean}, // whether to put top summary: {type: String}, // Body: {type: String },
  categories:[{ type: mongoose.SchemaTypes.ObjectId, ref:'Category'}]}) // ref:category foreign key relationship, an article can have more than one category. Exports of articles module.exports = mongoose. Model (exports of articles module.exports = mongoose.'Article', schema, 'articles'); 

Copy the code

In the table of articles, it is worth mentioning that mongoose is a new object model tool of MongoDB. Mongoose is a MongoDB NodeJS driver developed based on Node-mongodb-native and can be executed in an asynchronous environment. At the same time, it is also an object model library for MongoDB operation, which encapsulates MongoDB’s common methods of adding, deleting, modifying and checking documents, making NodeJS operation of MongoDB database more flexible and simple. We can still add mongoose by yarn Add Mongoose.

4. User table user.js code:

// blog Schema const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const schema = mongoose.Schema({
  username: {
    type: String
  },
  password: {
    type: String, // When retrieving user data, do not retrieve the password:false, // select queryset(val) { 
      returnBcrypt. hashSync(val, 10) // no plaintext password}}, // the user and the article relationship? }) // model -> mongodb store does exactly what? mongoose module.exports = mongoose.model('User', schema, 'users')

Copy the code

There is a bcrypt encryption and decryption algorithm. You need to add the bcrypt method through YARN Add to encrypt and decrypt the password entered by the user.

5. Article classification table category.js.

// blog Schema const mongoose = require('mongoose');

const schema = mongoose.Schema({
  title: { type: String}}) // model -> mongodb store does exactly what? mongoose module.exports = mongoose.model('Category', schema, 'categories')

Copy the code

Next is the front end.

  1. Vue router has two modes: Hash mode and history mode. This is the hash mode and history mode.
  • Hash mode: The principle behind hash mode is the onHashChange event, which can be listened for on the window object: the code above can change the page font color by changing the hash, which is not very useful, but illustrates the principle somewhat. More importantly, because urls that change the hash are logged by the browser, you’ll see that the browser works both forward and backward, and the page font color changes when you click back. As a result, even though the browser did not request the server, the page state was associated with the URL one by one, which was later given the heroic name front-end routing and became standard in single-page applications.
  • The history of routing: With the advent of the History API, the front-end routing began to evolve. In the previous hashchange, you can only change the url fragment after #, while the history API gives the front-end complete freedom. The history API can be divided into two parts. Switch and modify the historical status, including the back, forward, go three methods, corresponding to the browser’s forward and backward, jump operation, have a classmate said, only forward and backward (Google) browser, not jump, well, long press the mouse on moving back, will come out all of the recorded history of the current window, thus can jump (maybe called jump more appropriate) :
history.go(-2); // Back twice history.go(2); // forward twice history.back(); / / back hsitory. Forward (); / / to go forwardCopy the code

The pushState and replaceState methods take three arguments :stateObj,title, and URL

history.pushState({color:'red'}, 'red'.'red'})
 
window.onpopstate = function(event){
    console.log(event.state)
    if(event.state && event.state.color === 'red'){
        document.body.style.color = 'red';
    }
}
history.back();
history.forward();
Copy the code

Pushstate stores the state of the page in a state object. When the page URL changes back to the same URL, you can retrieve the state object using the event. State method to restore the page state, such as the color of the page, the location of the scroll bar, the reading progress, and so on. The page state of the component’s switch can be stored in state.

What the history mode is afraid of: With the History API, we lose the ugly #, but it also has a problem: not afraid to go forward, not back, but afraid to refresh, F5 (if the back end is not ready), because the refresh is actually requesting the server, not playing virtual.

  1. In Vue, we need to add a route to index.js under the Router folder in order to import the Vue project we created. The code is as follows:
// Import vue project add project path import vue from'vue'
import VueRouter from 'vue-router'
import Home from '.. /views/Home.vue'
import Main from '.. /views/Main.vue'
import Article from '.. /views/Article.vue'
import Tag from '.. /views/Tag.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about"* /'.. /views/About.vue'}, // list page {path:'/main',
    name: 'main', Component: Main}, // article {path:'/article/:id',
    name: 'article', component: Article}, // How many articles under each category {path:'/tag',
    name: 'tag',
    component: Tag
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

Copy the code

When creating an article page, its path looks like this: path: ‘/article/:id’, where the ID represents the dynamic route to view different articles based on the ID.

  1. Now that we have introduced the VUE page, we have to create the corresponding file. So I views directory. The main new vue, the article. The vue, the tag. Vue file.
  • The project directory of the file
  1. Finally, we create component files under the Components directory: header components, foot components, load components, comment components, and article project components that blogs reuse.

The execution result

  • Localhost: 8081 port
  • Localhost: 3001 port

Router + Views + Components router + Views + Components

Package online

  1. usenpm run buildCommand to package the Web file asdist, put the file in the server directory, and change the file name to Web. Launch the project and launch the backend.
  2. Go back to the back-end server directory and add the code:
app.use('/', express.static(__dirname + '/web'))

app.listen('3001', async(req, res) => {
  console.log('http://localhost:3001');
})
Copy the code

In this case, express,static is the static resource provided by Express, and then the contents of the package are displayed. The back end is waiting for you to give you a package of the static resource packaged by Vue. The back end puts the package into the server, starts the root route, gives it to the Web directory, and then the network side can access it.

Summarize the project execution sequence

  • After vue is written, NPM run Build generates a package of static files.
  • The static file package is placed in the server directory.
  • Getting vUE out there.
  • Finally drive on port 3001 (online)

The end of the

Article see now also end, the first time to write an article, if there is a mistake on the trouble we point out to me! If you feel good, don’t forget to click 👍 to go oh!

Finally, attach the Github address

  • Source address: blog