I thought about making a personal website, but I felt the process was too tedious and delayed for technical reasons. I bought a server on June 18, so just do it might be a waste.

To prepare

Do a simple version of the website, write this article is mainly to sort out their ideas, mainly involving :mysql, node, AXIos request, Vue package file upload to the server, Nginx, PM2 management node service these parts, I will respectively describe the construction process of these aspects.

The mysql database

Before this did not contact the database, the impression is to add, delete, change and check. I decided to write node background system to learn the syntax of mysql, here recommend myself these days to see the B station mysql video believe that your SQL statement will also write the bar.

In fact, the most used for the front end is to check, and then prepare to write the project before establishing a database, according to the increase of the page, increase the table in the database. For specific syntax, you can refer to the materials or watch the videos I recommend.

node

With the data, we need to use JS to manipulate the data in the database. Mysql > create a pool of connections to the mysql database. Mysql > create a pool of connections to the mysql database.

connection.query('SELECT * FROM `books` WHERE `author` = "David"'.function (error, results, fields) {});
Copy the code

Although I can write some SQL statements, BUT I do not use this JS library, I prefer sequelize to write simple and elegant. With the Sequelize library, we need to create a Model(the equivalent of a table in a database) that can be used to add, delete, change, or query data in a table. We’ll write some code like this:

Const sequelize = new sequelize ('minprogram'.'root'.'password', {
  host: 'localhost',
  dialect: 'mysql'}) // Specify a table const User = sequelize.define('user',
  {
    id: {
      type: Sequelize.STRING(10),
      primaryKey: true,
      autoIncrement: true
    },
    avatar: Sequelize.STRING(100),
    createdAt: Sequelize.BIGINT,
    updatedAt: Sequelize.BIGINT
  },
  { timestamps: false})Copy the code

After having the model model, we can start to operate the database. We can store the methods of operating data separately in the corresponding business logic, such as:

// user.js
const User = require('./model')
async function findAll() {
  return User.findAll()
}
async function createUserId(options) {
  return User.create(options)
}
async function getId(id) {
  return User.findAll({
    where: { id: id }
  })
}
module.exports = {
  findAll,
  createOpenid,
  getOpenid,
  updateTime
}
Copy the code

—————— split line ——————-

Now that you have the ability to manipulate your database, you can start writing some background logic and interfaces. For example, to do a login authentication, determine (whether there is the user, user password is correct) logic. To sort out the logic of the idea:

  1. When the login button is clicked, the login interface is invoked, and the server queries whether the user name exists in the database according to the user name (there are no multiple same user names, and this situation should be avoided during registration to remind the user that the user has registered).
  2. If no data is found in the database, the user name is not registered
  3. When you query the database, the password is inconsistent with the entered password, indicating that the password is entered successfully
  4. You can also set the login expiration and so on, so far it has not been done, so it is considered successful login
// The project uses the KOA framework // const jsonMine ='application/json'

router.get('/vue/login', async ctx => {
    const { username, password } = ctx.request.query
    const allList = await findUserByName(username)
    if (allList.length === 0) {
      handle(ctx, ' ', 1, 'This user is not registered')}else {
      if(allList[0].password ! == password) { handle(ctx,' ', 1, 'Password error')}else {
        handle(ctx, ' ', 0, 'Successful landing'}}}) // Process the returned data uniformlyfunction handle(ctx, data, code = 0, message = 'success') {
  ctx.type = jsonMine
  ctx.body = {
    code,
    data,
    message
  }
}
Copy the code

Axios requests a cross-domain problem

I’m just wrapping axios a little bit, and then I’m going to call the backend service and I’m going to set the port number to 8082.

import axios from 'axios'
export default ({ api, params }) => {
  const baseURL = 'http://' + window.location.hostname + : '8082'
  return axios({
    url: api,
    method: 'get',
    baseURL,
    // headers: { 'client-test': 'cors' },
    params,
    'Content-Type': 'application/x-www-form-urlencoded'
  }).then(res => {
    const { status } = res
    if (
      (status >= 200 && status < 300) ||
      status === 304 ||
      status === 302
    ) {
      return new Promise((resolve, reject) => {
        resolve(res.data)
      })
    } else {
      return Promise.reject(
        new Error(
          `${'*'.repeat(10)}Status:${status}The ${The '*'.repeat(
            10
          )}\n ${'*'.repeat(10)}API:${'*'.repeat(10)}\n ${The '*'.repeat(
            10
          )}  `
        )
      )
    }
  })
}
Copy the code

Cross-domain pair problems occur. The console has an error that requires us to set the background to allow access to the domain. Access-control-allow-origin = access-Control-allow-Origin It is possible to write a middleware, cers.js, that handles all routes uniformly:

  • The core code islet origin = options.origin || ctx.get('Origin') || '*' ctx.set('Access-Control-Allow-Origin', origin)
// cors.js
module.exports = function crossOrigin(options = {}) {
  const defaultOptions = {
    allowMethods: ['GET'.'PUT'.'POST'.'PATCH'.'DELETE'.'HEAD'.'OPTIONS']
  }

  options = Object.assign({}, defaultOptions, options) 
  return async functionCors (CTX, next) {// Set to allow access to the background pair of fields, you can set, or the request header origin, or all fields can be accessedlet origin = options.origin || ctx.get('Origin') | |The '*'
    ctx.set('Access-Control-Allow-Origin', origin)

    if (ctx.method === 'OPTIONS') {
      if (options.allowMethods) {
        ctx.set('Access-Control-Allow-Methods', options.allowMethods.join(', '))
      }
      // Access-Control-Allow-Headers
      if (options.allowHeaders) {
        ctx.set('Access-Control-Allow-Headers', options.allowHeaders.join(', '))}else {
        ctx.set(
          'Access-Control-Allow-Headers',
          ctx.get('Access-Control-Request-Headers')
        )
      }

      ctx.status = 204 // No Content
    } else {
        ctx.set('Access-Control-Allow-Credentials'.'true')
      }
      await next()
    }
  }
}

Copy the code

Vue packages files and uploads them to the server

The client accesses the server and gets the data to update the UI and state. Wrap the finished code in webpack. The following files are generated, and the next step is to send the dist folder to the specified directory on the server.

  • The sending steps are as follows
  1. Tar -cvf dist. Tar dist Compress the dist folder in the root directory to generate the dist. Tar file
  2. SCP dist. Tar [email protected]:/repo/dist Upload the dist. Tar file to the service path
  3. Tar -xvf dist Decompress the dist. Tar file to restore the dist folder

Nginx proxy

Using the nginx proxy to point to the server’s local index.html file, when accessing the domain name is equivalent to opening the server specified directory index.html file. If nginx is installed on the server, run the vi /etc/nginx/nginx.conf command to open the configuration file. Include /etc/nginx/conf.d/*.conf; include /etc/nginx/conf.d/*.conf;

Configuration files at the end of all.conf files in conf.d are imported. So for your comfort, create a new html.conf file in /etc/nginx/conf.d to write your own nginx configuration.

server { listen 8980 ; Server_name 118.31.127.59; root /repo ; location /dist { index index.html; }}Copy the code

This configuration specifies the root directory through root and the URI through location. When the page access 118.31.127.59:8980 / repo/dist can open the directory when the index is HTML file.

  • Why can’t I open the HTML file in dist folder on the server through nginx agent? The key is the path. If you want to open it correctly in the local dist folder, you need the path to start with file://, whereas the server uses nginx to specify the root directory as /repo to get the correct file path.

service

  • Use PM2 to manage node server code
    1. Pm2 ecosystem executes in the root directory of the (local) project, generates configuration files, and specifies service addresses and Github addresses
    2. Pm2 deploy file.config. js production setup
    3. Deploy server.config. js production
    4. Pm2 start app.js on the server to start the Node service

Building a personal website for the first time

The problem is that the page takes too long to load. There are a lot of places worth learning and optimizing, welcome 👏 big guy in the message area to give me suggestions and exchanges.