「初學者商城」- 搭建基礎架構(後臺管理系統)

1. 前言


後臺管理系統面對的羣體還是很廣的。

項目使用Vue+Element搭建;在當前搭建中會使用vue-cli腳手架快速創建一個Vue項目,並且能請求接口獲取到數據。

現在就來創建它,運行它。


2. 源碼


完整項目地址:https://github.com/intomylife/osc-front

v1.0 標籤地址:https://github.com/intomylife/osc-front/releases/tag/v1.0

v1.0 下載地址:ziptar.gz

注:對於標籤的說明「初學者商城」- 寫在最前面 #5.1


3. 環境


  • node 12.11.1
  • npm 6.11.3
  • vue 2.9.6

4. 工具


  • Visual Studio Code

5. 搭建


5.1 創建項目

  1. 打開終端
  2. 輸入命令vue如果不存在則輸入命令sudo npm install -g vue-cli全局安裝 vue-cli
  3. 進入到項目預存放目錄
  4. 輸入命令vue init webpack projectName在當前目錄創建一個基於 webpack 的項目
  5. 接下來就是填寫一些關於項目的信息就創建完畢
MacBook-Pro:Downloads zouwencong$ vue init webpack osc-front

? Project name osc-front
? Project description A Vue.js project
? Author 鄒文聰 <[email protected]>
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? No
? Set up unit tests No
? Setup e2e tests with Nightwatch? No
? Should we run `npm install` for you after the project has been created? (recom
mended) npm

   vue-cli · Generated "osc-front".


# Installing project dependencies ...
# ========================
...省略部分...
# ========================

To get started:

  cd osc-front
  npm run dev
  
Documentation can be found at https://vuejs-templates.github.io/webpack
  1. Project name(項目名稱):直接回車,使用默認,後面也可以更改
  2. Project description(項目描述):直接回車,使用默認,後面也可以更改
  3. Author(作者信息):直接回車,使用默認,後面也可以更改
  4. Vue build(是否安裝編譯器):直接回車
  5. Install vue-router?(是否安裝vue路由):回車表示yes,這裏選擇安裝,直接回車
  6. Use ESLint to lint your code?(是否校驗代碼規範): 輸入n,回車;在後續博客中會專門來安裝這個插件
  7. Set up unit tests(是否安裝單元測試工具):輸入n,回車
  8. Setup e2e tests with Nightwatch?(是否安裝模擬測試工具):輸入n,回車
  9. Should we run npm install for you after the project has been created? (recom
    mended)(使用哪種方式安裝依賴包)
    :直接回車,使用npm來安裝依賴
  10. 創建成功後,就可以運行了
MacBook-Pro:Downloads zouwencong$ cd osc-front
MacBook-Pro:osc-front zouwencong$ npm run dev

> [email protected] dev /Users/zouwencong/Downloads/osc-front
> webpack-dev-server --inline --progress --config build/webpack.dev.conf.js

 13% building modules 25/31 modules 6 active ...ncong/Downloads/osc-front/src/App.vue{ parser: "babylon" } is deprecated; we now treat it as { parser: "babel" }.
 95% emitting                                                                        

 DONE  Compiled successfully in 1681ms                                              17:45:38

 I  Your application is running here: http://localhost:8080
  1. 訪問http://localhost:8080/即可看到Vue主頁面
  2. ctrl+c先停止運行
  3. 使用vsCode打開代碼目錄

5.2 更改端口

注:習慣性會把前端頁面端口更改爲9527

  1. 找到config - index.js文件並打開
  2. 搜索port: 8080
  3. 8080更改爲9527

5.3 跨域

注:這裏主要解決的是開發時請求跨域問題

  1. 找到config - index.js文件並打開
  2. 搜索proxyTable: {}
  3. 配置如下
	proxyTable: {
      '/api' : {
        // target: 'https://xxx.com',
        target: 'http://127.0.0.1:8000',
        changeOrigin: true,
        pathRewrite: {
            '^/api': ''  // api 開頭的接口都使用此代理,如果添加了此行代碼,那麼意思就是在接口中去掉 api
        },
      }
    },
  1. 這裏配置後,項目中以/api開頭的請求都會被攔截下來,轉發到地址http://127.0.0.1:8000,並截取/api部分
  2. 例如地址http://127.0.0.1:9527/api/baseService請求會轉發到地址http://127.0.0.1:8000/baseService
  3. 爲什麼是轉發到8000端口?因爲8000是接口中的網關端口

5.4 環境變量

注:項目中專門有一個地方用來存放環境變量,並且不同的環境變量(開發、測試,生產等)由單獨的文件來存放

開發環境:

  1. 找到config - dev.env.js文件並打開
  2. 添加VUE_APP_BASE_APIVUE_APP_BASE_URL,如下
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  VUE_APP_BASE_API: '"/api"',
  VUE_APP_BASE_URL: '"/baseService"'
})
  1. VUE_APP_BASE_API用來拼接到請求的開頭部分,值/api也剛好是對應上面跨域中會被攔截的請求的開頭
  2. VUE_APP_BASE_URL用來拼接到請求的中間部分,值baseService也剛好是對應接口中網關路由攔截的請求的開頭

生產環境:

  1. 找到config - prod.env.js文件並打開
  2. 同樣添加VUE_APP_BASE_APIVUE_APP_BASE_URL,如下
'use strict'
module.exports = {
  NODE_ENV: '"production"',
  VUE_APP_BASE_API: '"/api"',
  VUE_APP_BASE_URL: '"/baseService"'
}
  1. 然而這裏生產時的用法與開發時不同,生產時跨域使用Nginx解決的,具體再後面部署時再展開,畢竟當前搭建只是在本地運行

5.5 封裝請求

注:這裏使用的是axios方式請求的數據

import axios from 'axios'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
  // baseURL: "http://xxx", // api 的 base_url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // debugger
    // Do something before request is sent
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// respone interceptor
service.interceptors.response.use(
  /**
   * 下面的註釋爲通過在response裏,自定義code來標示請求狀態
   * 當code返回如下情況則說明權限有問題,登出並返回到登錄頁
   * 如想通過xmlhttprequest來狀態碼標識 邏輯可寫在下面error中
   * 以下代碼均爲樣例,請結合自生需求加以修改,若不需要,則可刪除
   */
  response => {
    console.log(response.data)
    return response
  },
  error => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service

  1. 專門建一個目錄,用來存放工具類,如當前文件存放至src - utils - request.js
  2. 這個封裝的請求工具類一共分爲五大部分
    ① 引入axios
    ② 創建axios實例,並配置baseURLprocess.env.VUE_APP_BASE_API,也就是上面剛剛配置的環境變量
    ③ 配置請求攔截器(可以用來設置統一的請求頭,如讓每個請求攜帶用戶憑證token
    ④ 配置響應攔截器(可以用來處理統一的響應結果,如不同的狀態碼做不同的處理)
    ⑤ 導出(對外輸出本模塊供調用)

5.6 封裝接口

注:一般每個功能模塊的接口都會寫在一個單獨的文件中,方便查閱方便管理

import request from '@/utils/request'

// 獲取訪問次數
export function getComeCounts() {
  return request({
    url: `${process.env.VUE_APP_BASE_URL}/visit/toVisit`,
    method: 'get'
  })
}
  1. 文件位置在:src - api - base.js
  2. 引入上面封裝好的請求工具類
  3. process.env.VUE_APP_BASE_URL:獲取環境變量
  4. url:請求地址,完整地址爲http://127.0.0.1:9527/baseURL/${process.env.VUE_APP_BASE_URL}/visit/toVisit->http://127.0.0.1:9527/api/baseService/visit/toVisit
  5. method:請求方式

5.7 調用接口

注:直接寫在了默認的HelloWorld.vue文件中(刪除了原有部分代碼)

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
// 引入接口
import { getComeCounts } from "@/api/base";

export default {
  name: "HelloWorld",
  data() {
    return {
      msg: ""
    };
  },

  created() {
    // 調用獲取訪問次數方法
    this.comeCounts();
  },

  mounted() {},

  methods: {
    // 獲取訪問次數
    comeCounts() {
      // 調用獲取訪問次數接口
      getComeCounts().then(res => {
        // 打印結果
        console.log("HelloWorld: " + res);
        // 設值
        this.msg = res.data;
      });
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
  1. 頁面加載時會調用this.comeCounts()方法
  2. comeCounts()方法調用了上面封裝的接口
  3. 把接口返回的數據賦值到了data()中,並顯示到頁面上

6. 啓動


6.1 接口

  1. 如何啓動接口請前往:「初學者商城」- 搭建基礎架構(接口)

6.2 後臺管理系統

  1. vsCode中打開終端(快捷鍵:ctrl+~
  2. 輸入npm install --save axios,安裝axios
  3. 輸入npm run dev,回車

7. 驗證


  1. 訪問http://localhost:9527
  2. 顯示success,表示成功

8. 結語


這也算是真正意義上的前後端分離了。阿,快樂。


9. 相關文章


9.1 準備工作

「初學者商城」- 寫在最前面

9.2 搭建基礎架構

「初學者商城」- 搭建基礎架構(接口)

「初學者商城」- 搭建基礎架構(後臺管理系統)  👀

「初學者商城」- 搭建基礎架構(部署)

9.3 搭建本地開發環境

「初學者商城」- 搭建本地開發環境(JDK)

「初學者商城」- 搭建本地開發環境(Maven)

「初學者商城」- 搭建本地開發環境(Redis)

「初學者商城」- 搭建本地開發環境(MySQL)

「初學者商城」- 搭建本地開發環境(MongoDB)

「初學者商城」- 搭建本地開發環境(ZooKeeper)

「初學者商城」- 搭建本地開發環境(Kafka)


希望能夠幫助到你

over




發佈了104 篇原創文章 · 獲贊 290 · 訪問量 43萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章